Joe.wang
Joe.wang

Reputation: 11793

Delete object in foreach

I got an exception which said:

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

when I call DeleteObject() in a ForEach loop. After I searched this question in google, I failed to find the answer yet, and I didn't found anything wrong with my code, below.

There exists one to many relationship between DHEntity and 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.
        }
    }
}

Upvotes: 2

Views: 439

Answers (1)

Joe.wang
Joe.wang

Reputation: 11793

The problem is that the object is from another Data Context.

The Context GetAllDHEntity used to fetch the item is not the one to Delete it, which is why that object's state doesn't exist.

Upvotes: 3

Related Questions