I'm trying to clone an entity using the SetValues method but I get the following error :
The instance of entity type 'TariffPeriod' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
Here is the code :
var period2 = _tariffRepository.GetPeriodFull(period.GUID);
var period3 = new TariffPeriod();
_appDbContext.TariffPeriods.Add(period3);
_appDbContext.Entry(period3).CurrentValues.SetValues(period2);
I see that the error is due to the value of the primary key being copied into the new entity. So, how do I copy the values without the key?
Thanks for your help Eric
One way is to create a new object and manually assign the property values using the existing object values. You can also use some kind of mapping utility if it supports deep copying. However, I will demonstrate two alternative ways to clone an Entity object using EF techniques.
The cloned object should be treated as new data and should create new Primary Keys and associate with Referential Integrity. Once the Entity Reference is cleared on the cloned object, the Framework will create temporary keys for associations (will treat this as a new Entity and follow the same logic).
To simply copy values from an existing entity to a new entity, you have two stable ways. Copy values to a local var first: Directly copy values from old entity to new entity. These methods are stable and not based on any Reflection tinkering. Ben is a passionate developer and software architect and especially focused on .NET, cloud and IoT.
You can even include child objects. When you are retrieving an entity or entities from a dataset, you can tell Entity Framework not to track any of the changes that you are making to that object and then add that entity as a new entity to the dataset. With using .AsNoTracking, the context doesn’t know anything about the existing entity.
You can try getting a clone of the period2 data and modify the Id before assigning to period3
var values = db.Entry(period2).CurrentValues.Clone();
values["Id"] = 0;
db.Entry(period3).CurrentValues.SetValues(values);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With