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

前端 未结 10 1220
终归单人心
终归单人心 2020-11-27 14:48

I am getting this error \"The object cannot be deleted because it was not found in the ObjectStateManager.\"

My code is:

    protected MyEntities sql         


        
10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 15:36

    Just a small clarification on the answer by Ladislav Mrnka (which should be the accepted answer).

    If like me, you've got code in a format like this:

    using (var context = new MyDataContext())
    {
        context.MyTableEntity.Remove(EntytyToRemove);
        var nrOfObjectsChanged = context.SaveChanges();
    }
    

    ..then this what you want to do:

    using (var context = new MyDataContext())
    {
        // Note: Attatch to the entity:
        context.MyTableEntity.Attach(EntityToRemove);
    
        context.MyTableEntity.Remove(EntityToRemove);
        var nrOfObjectsChanged = context.SaveChanges();
    }
    

    Perhaps this seems obvious, but it was not clear to me initially that it is necessary to specify the entity to attatch to, and not just the context.

提交回复
热议问题