我有一个例外,它说:
无法删除该对象,因为它在 ObjectStateManager 中找不到
当我循环调用DeleteObject()
时。ForEach
在谷歌搜索这个问题后,我还没有找到答案,我没有发现我的代码有任何问题,如下所示。
DHEntity
和之间存在一对多的关系DHEntityVersion
。
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.
}
}
}