2010-11-15 63 views

回答

1

這是我做通用深副本:

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

看來你可以用一個StackOverflowException結束了,如果你的實體有一個循環引用。 – 2011-04-03 13:58:57

+0

爲我工作得很好。 – Joshy 2012-04-27 05:58:46

0

我相信這已經問過。無論哪種方式,你需要小心這一點。存在克隆過程使用反射的危險,因此在屬性被詢問反射時調用EF支持的延遲數據加載。

如果你這樣做,確保無論你用什麼來克隆實例作爲實際的POCO類(我假設你正在使用POCOS),這應該解決延遲加載問題。只是一個想法。

+0

如果您禁用延遲加載,延遲數據加載仍然是一個問題嗎? – RPM1984 2010-11-15 11:20:59

+0

沒有。只要你能處理空值。應該沒事。 – Slappy 2010-11-15 22:48:44

0

我懷疑你不一定需要一個深層克隆 - 一個新的對象與被複制的屬性通常就足夠了 - 這樣,如果一個屬性被重新分配,它不會混淆你克隆的原始EntityObject。

順便說一下,我看到延遲加載沒有問題 - 這是你想要的。

來源: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; 
} 

可以與entites的複製到克隆的對象現在也;假設你有一個實體:客戶,其中有導航屬性:訂單。然後,您可以通過使用上述方法複製的客戶和他們的訂單:

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

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