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 start
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.