Entity Framework 6: Clone object except ID

c# entity-framework entity-framework-6 mvvm


In my MVVM program I have a Model class (say MyModel) from which I have an instance of reading from the database (using Entity Framework). When retrieving the object I'm presenting all the data to the user. Later on the user will be modifying some fields.
What I want is to create the same object except for it's ID (since that ID is the primary key and auto incremented).
So how could I approach this? I don't want to copy all fields one by one, this is not a robust approach. Because perhaps in the future the model may be modified, so this way I will have to take that into account in the cloning method.

So is there any elegant way to copy the object and when saving in the database, it's ID gets auto incremented again? (Setting the ID to null gives me a compiler error, because it's of type int).

7/22/2017 12:51:42 AM

Accepted Answer

I noticed that there is no need for copying. Apparently when adding an instance of a model to the database (even if the ID is set to one that already exists in the database), Entity Framework inserts a new row in the database and auto-increments it's primary key. So this functionality is already built-in into EF. I didn't know this, sorry.
Just for clarity's sake here is an example:

using(var database = new MyDbContext()) {
    MyModel myModel = database.FirstOrDefault(m => m.SomeProperty == someValue);
    myModel.SomeOtherProperty = someOtherValue; //user changed a value
    database.MyModels.Add(myModel); //even though the ID of myModel exists in the database, it gets added as a new row and the ID gets auto-incremented 
7/29/2018 11:55:01 AM

Popular Answer

Lori Peterson has suggested using .AsNoTracking() to perform cloning in EF6. I'm using this method and can confirm that it works. You can even include child objects.

var entity = context.Entities
                    .Include(x => x.ChildEntities)
                    .FirstOrDefault(x => x.EntityId == entityId);

entity.SomeProperty = DateTime.Now;


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.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow