Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning data on Entity Framework [duplicate]

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.

like image 201
Tx3 Avatar asked Feb 02 '10 15:02

Tx3


2 Answers

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(); 
like image 53
ChrisNel52 Avatar answered Sep 22 '22 14:09

ChrisNel52


public static EntityObject Clone(this EntityObject Entity) {     var Type = Entity.GetType();     var Clone = Activator.CreateInstance(Type);      foreach (var Property in Type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.SetProperty))     {         if (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference<>)) continue;         if (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>)) continue;         if (Property.PropertyType.IsSubclassOf(typeof(EntityObject)))  continue;          if (Property.CanWrite)         {             Property.SetValue(Clone, Property.GetValue(Entity, null), null);         }     }      return (EntityObject)Clone; } 

This is a simple method I wrote. It should work for most people.

like image 21
Tomasi Avatar answered Sep 21 '22 14:09

Tomasi