【问题标题】:InvalidOperationException on Attaching POCO entity to context将 POCO 实体附加到上下文时出现 InvalidOperationException
【发布时间】:2011-06-27 06:57:30
【问题描述】:

我在将 POCO 实体附加到其上下文时遇到了问题。我收到带有以下消息的 InvalidOperationException:

ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象。

实际上,我只有一个项目得到了这个例外。当我附加除此特定项目之外的其他项目时,我没有遇到这种异常。

我正在使用以下代码:

 ItemDocument itemDocument = new ItemDocument();
 Item item = GetItem(itemID); // the item I got here is detached
 using (SampleContext context = new SampleContext()){
      context.Items.Attach(item);  // I got the exception here
      context.LoadProperty(item, "Classifications");
      itemDocument.Classification = item.Classifications.Select(c => c.Name).ToList();
 }

谢谢。

【问题讨论】:

    标签: c# entity-framework-4 poco


    【解决方案1】:

    在使用相同的键附加新对象之前尝试从上下文中 Detach 旧对象怎么样?

    【讨论】:

    • 其实老对象已经分离了。我也不知道为什么它只是一个项目而不是其他项目出错。我猜它与分类导航属性有关。当我注释掉加载该属性的代码行时,我没有遇到这个问题。
    • Classification 不是自动加载的,你无意中强制 ef 重新加载它吗?
    • 不,它不是自动加载的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 2011-06-04
    • 2011-09-05
    • 2021-11-26
    相关资源
    最近更新 更多