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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With