Quantcast
Channel: Cloning Entity Framework entities - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 2

Cloning Entity Framework entities

0
0

I'm currently writting piece of logic which copies entities from one user account to another. My current strategy in doing this is like that: Consider the following code:

 public class MobileOrderSettings:ICloneable
{
    public long Id { get; set; }
    public bool allowCash { get; set; }
    public int deliveryPrice { get; set; }
    public int deliveryTreshold { get; set; }
    public bool orderingEnabled { get; set; }
    public bool paymentsEnabled { get; set; }
    public int shippingType { get; set; }

    public virtual MobileApp MobileApp { get; set; }

    public object Clone()
    {
        var copy = CopyUtils.ShallowCopyEntity(this);
        copy.Id = default(int);
        copy.MobileApp = null;
        return copy;
    }
}

The ShallowCopyEntity method defined like in this way:

 public static TEntity ShallowCopyEntity<TEntity>(TEntity source) where TEntity : class, new()
    {

        // Get properties from EF that are read/write and not marked witht he NotMappedAttribute
        var sourceProperties = typeof(TEntity)
                                .GetProperties()
                                .Where(p => p.CanRead && p.CanWrite &&
                                            p.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute), true).Length == 0);
        var notVirtualProperties = sourceProperties.Where(p => !p.GetGetMethod().IsVirtual);
        var newObj = new TEntity();

        foreach (var property in notVirtualProperties)
        {

            // Copy value
            property.SetValue(newObj, property.GetValue(source, null), null);

        }

        return newObj;

    }

So, as you can see, I firstly copy all fields which is not virtual, reassing Id value and then perform copy of the dependent object(collection)(In this particular situation MobileOrderSettings depends on MobileApp entity, so I make MobileApp null, and in MobileApp Clone menthod I assign MobileOrderSettings virtual field the copy of MobileOrderSettings). Is this approach is good, or you can suggest any better solution?


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images