2013-07-18 50 views
1

我有以下的LINQ到SQL對象(例如)清除主鍵後,深克隆對象

class Parent{ 
    int id; // primary key 
    IEnumerable<Child> children; 
} 

class Child{ 
    int id; // primary key 
    string field1; 
    int field2; 
} 

我需要深克隆一個Parent,並將其保存到數據庫中,但與孩子的副本,即不參考現有的孩子。

我用this method做克隆,但在尋找的優雅的方式,通過家長和孩子們的屬性迭代(因爲可能有大量的子對象,級聯遠遠超出1級深)和將其主鍵設置爲0,這樣當我將克隆的對象提交給數據庫時,LINQ to SQL負責創建新的子項。

回答

2

你可以試試它採用System.Reflection以下擴展方法:

public static T DeepCopy<T>(this T parent) where T : new() 
{ 
    var newParent = new T(); 
    foreach (FieldInfo p in typeof(T).GetFields()) 
    { 
     if (p.Name.ToLower() != "id") 
      p.SetValue(newParent, p.GetValue(parent)); 
     else 
      p.SetValue(newParent, 0); 
     if (p.FieldType.IsGenericType && 
      p.FieldType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) 
     { 
      dynamic children = p.GetValue(parent); 
      dynamic newChildren = p.GetValue(parent); 
      for (int i = 0; i < children.Length; i++) 
      { 
       var newChild = DeepCopy(children[i]); 
       newChildren.SetValue(newChild, i); 
      } 
     } 
    } 
    return newParent; 
} 
+0

很管用的,謝謝。 – Jimbo