【发布时间】:2014-06-13 18:48:32
【问题描述】:
我正在使用以下方法尝试使用实体框架更新对象:
public static void UpdateItem(Item updatedObject) {
using (var context = new DbContext())
{
context.MyObjectsPropertys.Attach(updatedObject);
context.Entry(updatedObject).State = EntityState.Modified;
context.SaveChanges();
}
}
附件出现错误:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
如果我尝试将 Attach 调用更改为 Add 调用 (object with same key already exists objectstatemanager),我会得到:
Cannot insert duplicate key in object 'database.Table'. The duplicate key value is (AttributeValue). The statement has been terminated.
我发现了很多关于这个错误的问题,但没有一个答案适用于我的情况:
我也尝试删除“附加”语句,只是按照Error multiple objects with the same key DbContext 中的建议进行状态更改,但这也没有用。
对我来说最令人沮丧的是,这与成功更新解决方案中其他内容的语句序列完全相同。
【问题讨论】:
-
你能检查出究竟是哪一行引发了错误吗?
标签: c# entity-framework asp.net-mvc-4