0

我需要克隆主和子實體。我在CodeProject上遇到了這個解決方案,似乎可以完成這項工作,請參閱:http://www.codeproject.com/Tips/474296/Clone-an-Entity-in-Entity-Framework-4如何將此EF克隆代碼轉換爲使用DBContext而不是EntityObject?

但是我使用EF5和DBContext,而此代碼使用EF4和EntityObject,所以我想知道我需要對它做什麼更改?

的代碼是:

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; 

}

調用代碼:

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

foreach(Order order in myCustomer.Orders) 
{ 
Order newOrder = CopyEntity(myObjectContext, order, true); 
newCustomer.Orders.Add(newOrder); 
} 

我張貼這裏對這個職位的反饋看不活動,我相信這是任何EF專業人士都可以回答的問題。

非常感謝提前。

回答

2

如果你想使用EF5 DbContext最簡單的方法實體的克隆是這樣的:

//clone of the current entity values 
Object currentValClone = context.Entry(entityToClone) 
           .CurrentValues.ToObject(); 

//clone of the original entity values 
Object originalValueClone = context.Entry(entityToClone) 
            .OriginalValues.ToObject(); 

//clone of the current entity database values (results in db hit 
Object dbValueClone = context.Entry(entityToClone) 
            .GetDatabaseValues().ToObject(); 
+0

謝謝你。很有幫助。 – SamJolly

0

你的代碼會工作只有在你的實體屬性有EdmScalarPropertyAttribute

或者你可以使用MetadataWorkspace得到實體財產

public static class EntityExtensions 
{ 
    public static TEntity CopyEntity<TEntity>(DbContext context, TEntity entity, bool copyKeys = false) 
     where TEntity : class 
    { 
     ObjectContext ctx = ((IObjectContextAdapter)context).ObjectContext; 
     TEntity clone = null; 
     if (ctx != null) 
     { 
      context.Configuration.AutoDetectChangesEnabled = false; 
      try 
      { 
       clone = ctx.CreateObject<TEntity>(); 
       var objectEntityType = ctx.MetadataWorkspace.GetItems(DataSpace.OSpace).Where(x => x.BuiltInTypeKind == BuiltInTypeKind.EntityType).OfType<EntityType>().Where(x => x.Name == clone.GetType().Name).Single(); 

       var pis = entity.GetType().GetProperties().Where(t => t.CanWrite); 
       foreach (PropertyInfo pi in pis) 
       { 
        var key = objectEntityType.KeyProperties.Where(t => t.Name == pi.Name).FirstOrDefault(); 
        if (key != null && !copyKeys) 
         continue; 
        pi.SetValue(clone, pi.GetValue(entity, null), null); 
       } 
      } 
      finally 
      { 
       context.Configuration.AutoDetectChangesEnabled = true; 
      } 
     } 
     return clone; 
    } 
}