Entity Framework data cloning

entity-framework

Question

I'm developing software that will allow users to build new products off of existing ones.

I now need to use Entity Framework to do copying and cloning actions. I first began by writing as follows:

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's not a very classy way to go about it. Is there a quick method to transfer data—aside from Guid, which has to be produced for new rows—or should I copy everything by hand?

Another option

To duplicate the properties, you might alternatively use EmitMapper or AutoMapper.

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

Accepted Answer

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

Popular Answer

You may just detach the entity from the database in Entity Framework to clone an entity.DataContext then add it once more to theEntityCollection .

context.Detach(entity);
entityCollection.Add(entity);

for EF6+, Update (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