问题描述
我有以下code以添加或更新实体对象。找到主键对对象的基础上,我添加或更新对象的响应。
I have following code to add or update the Entity object. finding the object by primary key, based on the response I am adding or updating the object.
添加记录的作品,但在更新过程中它给这个错误消息具有相同键的对象已经存在于ObjectStateManager该ObjectStateManager无法跟踪使用相同的密钥多个对象
Adding record works, but during update its giving this error message "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"
在我的MSSQL数据库,我只有一个记录。
In my MSSQL database I have only one record.
var v = db.Envelopes.Find(model.ReportDate, model.Service);
if (v == null)
{
db.Envelopes.Add(model);
db.SaveChanges();
ViewBag.status = "Record Add successfully";
ModelState.Clear();
}
else
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
}
我怎样才能解决这个问题?
How can I fix this error message?
推荐答案
正如@anon一旦你使用相同的密钥加载的实体,你不能将模型提及。这些变化必须应用到连接实体。取而代之的是:
As mentioned by @anon you can't attach model once you loaded the entity with the same key. The changes must be applied to attached entity. Instead of this:
db.Entry(model).State = EntityState.Modified;
使用:
db.Entry(v).CurrentValues.SetValues(model);
这篇关于具有相同键的对象已经存在于ObjectStateManager。该ObjectStateManager不能用相同的密钥跟踪多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!