2

我有一个例外,它说:

无法删除该对象,因为它在 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.
        }
    }
}
4

1 回答 1

3

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

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

于 2013-01-23T03:09:31.337 回答