删除一个对象并使用相同的键插入另一个对象

Delete an object and Insert another with same key

请考虑此代码:

var tmpCurrentRecord = ent.Mytbl.Where(o => o.ID == CurrentRecord.ID).First();                        
ent.ObjectStateManager.ChangeObjectState(tmpCurrentRecord, System.Data.EntityState.Deleted);
ent.Mytbl.DeleteObject(tmpCurrentRecord);

ent.Mytbl.AddObject(NewRecord);

ent.SaveChanges();

我想重置特定列的值 record.Because 该列的计数约为 70 列,我想删除记录并使用相同的主键再次插入。但是我得到这个错误:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

我该如何解决这个问题?

您可以分离旧对象,然后附加新对象。看到这个 overview on MSDN

这消除了执行 2 次 SaveChanges() 的需要,并且应该更快(索引等的更新更少)