2009-12-15 176 views
1

原諒愚蠢的newby問題,但... 我正在將數據從一個表移動到另一個表。目標表模式與源表完全相同,只是它有幾個額外的列。 Linq to SQL生成類來表示每個表。如果我有一個源對象,我該如何從它創建一個目標對象?例如,源對象具有屬性A,B,C。目標對象具有A,B,C,X,Y。我想要做的事,如:從另一個對象創建對象

Destination dest = new Destination(Source source, int x, int y) 
    { 
    this.X = x; 
    this.Y = y; 
    ... 
    // somehow set all the destination properties to 
    // their corresponding source value 
    } 

有一種優雅的方式比顯式設置每個屬性做到這一點其他的? 我可以讓Destination從源代碼繼承嗎?這會有幫助嗎?

回答

1

如果類型無關,MiscUtil有:

Destination dest = PropertyCopy<Destination>.CopyFrom(source); 

然後手動設置:

dest.X = x; 
dest.Y = y; 

你可以寫或者一個轉換方法/操作員,但你需要保持它( PropertyCopy是自動的)。


重申你的繼承點;我認爲這不太合適。你可能做部分類的東西,但它不會與LINQ到SQL一起工作,如果你這樣做(它處理繼承本身,並不會喜歡你這樣做)。

0

您可以在您傳遞源代碼的對象中使用複製構造函數,並手動將它的字段複製到目標。但是,這需要大量的手動編碼。

您也可以使用像AutoMapper這樣的庫爲您自動執行此操作。您可以定義該源可映射到目標(無非是),並根據項目名稱爲您解決問題。另外,如果你純粹只是移動數據(我假設在一個數據庫中),你可以使用純SQL來做到這一點,而不需要任何代碼嗎?

2

爲什麼不能用Reflection創建自己的自動轉換?你可以做一些事情來的

class Program { 
    static void Main(string[] args) 
    { 
     Source item1 = new Source(2, 3, 4); 
     Destination item2 = new Destination(item1, ContinueCopy); 

     Console.WriteLine(string.Format("X: {0}\n Y: {1}", item2.X, item2.Y)); 
     Console.ReadKey(); 
    } 

    public static bool ContinueCopy(string name, Type type) 
    { 
     if (name == "X" && type == typeof(int)) return false; 

     return true; 
    } 
    } 

    public class Source { 
    public Source() { } 
    public Source(int x, int y, int z) 
    { 
     myX = x; 
     myY = y; 
     myZ = z; 
    } 
    private int myX; 
    public int X 
    { 
     get { return myX; } 
     set { myX = value; } 
    } 

    private int myY; 
    public int Y 
    { 
     get { return myY; } 
     set { myY = value; } 
    } 

    private int myZ; 
    public int Z 
    { 
     get { return myZ; } 
     set { myZ = value; } 
    } 
    } 


    public class Destination { 
    public delegate bool ContinueCopyCallback(string propertyName, Type propertyType); 

    public Destination() : this(0,0) { } 
    public Destination(int x, int y) 
    { 
     myX = x; 
     myY = y; 
    } 
    public Destination(Source copy) : this(copy, null) { } 
    public Destination(Source copy, ContinueCopyCallback callback) 
    { 
     foreach (PropertyInfo pi in copy.GetType().GetProperties()) 
     { 
      PropertyInfo pi2 = this.GetType().GetProperty(pi.Name); 
      if ((callback == null || (callback != null && callback(pi.Name, 
       pi.PropertyType))) && pi2 != null && pi2.GetType() == pi.GetType()) 
      { 
       pi2.SetValue(this, pi.GetValue(copy, null), null); 
      } 
     } 
    } 

    private int myX; 
    public int X 
    { 
     get { return myX; } 
     set { myX = value; } 
    } 

    private int myY; 
    public int Y 
    { 
     get { return myY; } 
     set { myY = value; } 
    } 
} 

調輸出將給item2.X值2和item2.Y的3

值時,也可以提供有一個回調的能力,這可以讓您對不希望自動複製的屬性名稱進行自定義過濾。您也可以將複製代碼編寫爲接受Source作爲參數的Destination的淺拷貝構造函數。

這是一種輕量級的方法,因爲您的需求非常簡單。

相關問題