Copy Entity Framework Object

前端 未结 5 1798
面向向阳花
面向向阳花 2021-01-31 21:52

I have a EF4.1 class X and I want to make copy of that plus all its child records. X.Y and X.Y.Z

Now if I do the following it returns error.

The property \'X.ID\

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 22:42

    Not sure if it works in 4.1, from http://www.codeproject.com/Tips/474296/Clone-an-Entity-in-Entity-Framework-4:

    public static T CopyEntity(MyContext ctx, T entity, bool copyKeys = false) where T : EntityObject
    {
        T clone = ctx.CreateObject();
        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);
    }
    

提交回复
热议问题