简体   繁体   中英

Clone an EF6 record with relations

I'm getting a record from EF6 with

Context
.MyRepo
.Include(p => p.MyRelation)
.AsNoTracking()
.SingleOrDefault(p => p.Uuid == recordUuid);

Then I try to insert a copy of the record zith

myRecord.Uuid = Guid.NewGuid();
myRecord.EntityKey = new System.Data.EntityKey("modelqualifiedname", "Id", 1726526);

Context.MyRepo.AddObject(myRecord);
Context.SaveChanges();

But it fails with this message

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

I tried to set the EntityKey to null , like it is in a new record; but it did not help. Any idea?

This object is already tracked by EF.

You have to either modify its key or change its state to Modified.

Context.MyRepo.Entry(myRecord).State = EntityState.Modified;

and then save it.

我认为您是由于子对象而出现错误,应该尝试为每个子对象设置一个新键。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM