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

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

Trying to get a handle on Entity Framework here and I am hitting some speed bumps... I have a Get() method that works fine and has been tested, but my Delete method is not working:

   public static void Delete(string name)     {         J1Entities db = new J1Entities();         db.DeleteObject(Get(name));         db.SaveChanges();     }

But I get the following error: Error: The object cannot be deleted because it was not found in the ObjectStateManager.

I ran the debugger, and the object inside the DeleteObject is correct... what am I missing? Thank you.

回答1:

Each EF object is tightly associated to the manager (for want of a better word) that created it. or to which it has been associated. Since you don't pass db to your Get method, I assume that Get has either used it's own J1Entities, or the object has been created standalone (perhaps deserialized).

In order to delete it, it must know about it first. That might mean by attaching an object to the manager - but in this case, it seems like an easier option is just to pass db into Get, so that the Get is done in the same context (since db will automatically attach objects that it creates itself).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!