I am creating software where user can create new product based on older product.
Now I need to make copying / cloning operations with Entity Framework. First I started writing like this:
foreach(sourcedata1 in table1) { ... create new table ... copy data ... create Guid ... add foreach(sourcedata2 in table2) { ... create new table ... copy data ... create Guid ... add ... and so on } }
Problem is that this not a nice way to do it. Is there any easy way clone information (except Guid that needs to be generated for new rows) or should I manually copy everything?
Other solution
You could also use EmitMapper or AutoMapper to do copying of the properties.
Using straight serialization, you can do this:
Using Reflection, but with lots more code you can do this: http://msmvps.com/blogs/matthieu/archive/2008/05/31/entity-cloner.aspx
To clone an Entity in Entity Framework you could simply Detach the entity from the DataContext
and then re-add it to the EntityCollection
.
context.Detach(entity);
entityCollection.Add(entity);
Update for EF6+ (from comments)
context.Entry(entity).State = EntityState.Detached;
entity.id = 0;
entity.property = value;
context.Entry(entity).State = EntityState.Added;
context.SaveChanges();