How make deep copy (clone) in Entity framework 4?

社会主义新天地 提交于 2019-12-02 21:29:47

问题


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


回答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);
        }
    }



回答2:


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.




回答3:


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);
}


来源:https://stackoverflow.com/questions/4182429/how-make-deep-copy-clone-in-entity-framework-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!