0

How make deep copy (clone) in Entity framework 4? I need get copy of the EntityObject with copies of all related objects.

Ivan
  • 1
  • 1
  • 1

3 Answers3

1

This is how I do generic deep copy:

    public static T DeepClone<T>(this T obj)
    {
        using (var ms = new MemoryStream()) {
            var bf = new BinaryFormatter();
            bf.Serialize(ms, obj);
            ms.Position = 0;
            return (T)bf.Deserialize(ms);
        }
    }
Simone
  • 11,655
  • 1
  • 30
  • 43
0

I suspect you do not necessarily need a deep clone - a new object the with the properties copied is usually enough - that way if a property is re-assigned it will not mess with the original EntityObject you cloned.

By the way I see no problem with deferred loading - that is what you want.

From: http://www.codeproject.com/Tips/474296/Clone-an-Entity-in-Entity-Framework-4

public static T CopyEntity<T>(MyContext ctx, T entity, bool copyKeys = false) where T : EntityObject
{
    T clone = ctx.CreateObject<T>();
    PropertyInfo[] pis = entity.GetType().GetProperties();

    foreach (PropertyInfo pi in pis)
    {
        EdmScalarPropertyAttribute[] attrs = (EdmScalarPropertyAttribute[])pi.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false);

        foreach (EdmScalarPropertyAttribute attr in attrs)
        {
            if (!copyKeys && attr.EntityKeyProperty)
                continue;

            pi.SetValue(clone, pi.GetValue(entity, null), null);
        }
    }

    return clone;
}

You can copy related entites to your cloned object now too; say you had an entity: Customer, which had the Navigation Property: Orders. You could then copy the Customer and their Orders using the above method by:

Customer newCustomer = CopyEntity(myObjectContext, myCustomer, false);

foreach(Order order in myCustomer.Orders)
{
    Order newOrder = CopyEntity(myObjectContext, order, true);
    newCustomer.Orders.Add(newOrder);
}
markmnl
  • 11,116
  • 8
  • 73
  • 109
0

I am sure this has been asked before. Either way you need to be careful of this. There is a danger that your cloning process uses reflection, thus invoking the deferred data loading supported by EF when the properties are interrogated for reflection.

If you are doing this make sure whatever you are using to clone boxes the instance as the actually POCO class (I am assuming you are using POCOS) this should get around the deferred loading issue. Just an idea.

Slappy
  • 4,042
  • 2
  • 29
  • 41