Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone an entity in Entity Framework Core?

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

like image 807
EricImhauser Avatar asked Aug 28 '17 08:08

EricImhauser


People also ask

How to clone an entity object in Entity Framework?

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.

What happens when you clone an object in a framework?

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).

How to copy values from an existing entity to a new entity?

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.

Can I include child objects in Entity Framework?

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.


1 Answers

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);
like image 142
grek40 Avatar answered Sep 21 '22 13:09

grek40