Cloning data on Entity Framework

前端 未结 6 1692
轻奢々
轻奢々 2020-12-02 09:53

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

6条回答
  •  眼角桃花
    2020-12-02 10:31

    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.

提交回复
热议问题