Entity Framework data cloning

entity-framework

Question

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.

1
51
2/15/2012 8:39:52 AM

Accepted Answer

15
10/31/2012 7:11:28 PM

Popular Answer

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();


Related Questions





Related

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