C# 错误:无法删除对象,因为在 ObjectStateManager 中找不到它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/449740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: The object cannot be deleted because it was not found in the ObjectStateManager
提问by naspinski
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:
试图在这里处理实体框架,但我遇到了一些减速......我有一个运行良好并经过测试的 Get() 方法,但我的 Delete 方法不起作用:
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.
但是我收到以下错误: 错误:无法删除对象,因为在 ObjectStateManager 中找不到它。
I ran the debugger, and the object inside the DeleteObject is correct... what am I missing? Thank you.
我运行了调试器,DeleteObject 中的对象是正确的……我错过了什么?谢谢你。
采纳答案by Marc Gravell
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).
每个 EF 对象都与创建它的管理器(因为想要更好的词)紧密相关。或与之相关联的。由于您没有传递db
给您的Get
方法,我假设Get
已经使用了它自己的方法J1Entities
,或者该对象是独立创建的(可能是反序列化的)。
In order to delete it, it must know about it first. That might mean by attachingan 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).
为了把它删除,就必须了解它第一次。这可能意味着通过将对象附加到管理器 - 但在这种情况下,似乎更简单的选择是db
传入Get
,以便Get
在相同的上下文中完成(因为db
会自动附加它自己创建的对象)。