我有一个例外,说:
无法删除对象,因为在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.
}
}
}
答案 0 :(得分:3)
问题是该对象来自另一个数据上下文。
用于获取项目的上下文GetAllDHEntity
不是Delete
它的那个,这就是该对象的状态不存在的原因。