ObjectStateManager中已经存在具有相同密钥的对象 [英] An object with the same key already exists in the ObjectStateManager
问题描述
我如何实现这个,
我想获得客户端的当前记录修改它,而不是更新我想将新记录添加到表格中以获取历史变更信息。
client c = new client();
using(DBEntities db = new DBEntities())
{
//获取客户端表中的当前记录
IQueryable< client> co = from p in db.client其中p.CUS_NUMBER == scd.cus_number&&& p.isCurrent == true select p;
c = co.First();
//更新电子邮件和地址
c.EMAIL = Helper.CleanInput(mymail@mm.com);
c.ADDRESS = Helper.CleanInput(123 Sheppard);
//而不是更新当前记录我想在表中添加新记录来保留历史变化
db.AddToclient(c);
db.SaveChanges();
//我收到错误
// ObjectStateManager中已存在具有相同密钥的对象。
//现有对象处于修改状态。一个对象只能在添加状态时再次添加到
// ObjectStateManager中。
完成错误
ObjectStateManager中已经存在具有相同键的对象。现有对象处于修改状态。如果对象处于添加状态,则只能将对象重新添加到ObjectStateManager中。
删除此代码 db.AddToclient(c);
,休息一切正常,你已经通过引用访问对象,所以不需要再添加它。当你调用 savechanges()
或使用克隆,如果要添加新对象 c = co.First()。克隆();
I have a scenario that could not find the solution for it and need some help How can I achieve this, I’d like to get current record for the client modify it and instead of update I’d like to add the new record to table for historical change information
client c = new client();
using (DBEntities db = new DBEntities())
{
// get current records in the client table for client
IQueryable<client> co = from p in db.client where p.CUS_NUMBER == scd.cus_number && p.isCurrent == true select p;
c = co.First();
//update email and and address
c.EMAIL = Helper.CleanInput("mymail@mm.com");
c.ADDRESS = Helper.CleanInput("123 Sheppard");
//instead of updating current record I'd like to add new record to the table to keep historical changes
db.AddToclient(c);
db.SaveChanges();
//I get error that
//An object with the same key already exists in the ObjectStateManager.
//The existing object is in the Modified state. An object can only be added to
//the ObjectStateManager again if it is in the added state.
Complete error
An object with the same key already exists in the ObjectStateManager. The existing object is in the Modified state. An object can only be added to the ObjectStateManager again if it is in the added state.
remove this code db.AddToclient(c);
,rest all is fine,You are already accessing the object by its reference so no need to add it again.It'll get modified when you call savechanges()
or use cloning if you want to add new object c = co.First().Clone();
这篇关于ObjectStateManager中已经存在具有相同密钥的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!