Entity Framework 6: Clone object except ID [closed]
Solution 1:
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
database.SaveChanges();
}
Solution 2:
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
.AsNoTracking()
.Include(x => x.ChildEntities)
.FirstOrDefault(x => x.EntityId == entityId);
entity.SomeProperty = DateTime.Now;
context.Entities.Add(entity);
context.SaveChanges();
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.