gpt4 book ai didi

c# - 在 foreach 中删除对象

转载 作者:行者123 更新时间:2023-11-30 22:21:18 25 4
gpt4 key购买 nike

我有一个异常(exception)说:

The object cannot be deleted because it was not found in the ObjectStateManager

当我在 ForEach 循环中调用 DeleteObject() 时。在谷歌搜索这个问题后,我还没有找到答案,而且我的代码也没有发现任何问题,如下所示。

DHEntityDHEntityVersion之间存在一对多的关系。

public IList<DHEntity> GetAllDHEntity(Guid packId)
{
using (DiaDataContext db = new DiaDataContext(ConnectionStrings.LogDB))
{
var subPackList = new List<DHEntity>();
subPackList = db.DHEntities.Include(d=>d.DHEntityVersions).Where(p => p.PackageId == packId).ToList();
return subPackList;
}
}

private void Delete()
{
using (DiaDataContext db = new DiaDataContext(ConnectionStrings.LogDB))
{
var subPacks = GetAllDHEntity(packId);////This method used another context. maybe it is the reason cause the problem .
foreach (var subpack in subPacks)
{
var vList = db.DHEntityVersions.Where(v =>v.DHEntityId == subpack.ID).ToList();
foreach (var version in vList)
{
db.DeleteObject(version);
}
db.DeleteObject(subpack);//the debugger stop here along with the exception I mentioned before.
}
}
}

最佳答案

问题是对象来自另一个数据上下文。

用于获取项目的上下文 GetAllDHEntity 不是用于Delete 的上下文,这就是该对象的状态不存在的原因。

关于c# - 在 foreach 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14471712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com