2010-03-16 67 views
1

我有2個表格,user和userprofile。 userprofile表包含許多類似於用戶表的字段。我需要做的是,點擊一個按鈕,我需要將用戶表的所有字段複製到userprofile表。將一個對象複製到另一個

How can I do that? 
+0

爲什麼被標記爲WPF問題? – 2010-03-16 22:21:15

回答

4

您可以創建用戶配置一個構造函數的用戶實例作爲參數,並做到這一點呢?不確定這是最好的方法,還是違反了良好的設計。在那裏有一個名爲AutoMapper的實用程序,它可以很好地推斷兩個看起來不相關的對象之間的鏈接,因此您可能想檢查一下,因爲它非常酷。

+0

Automapper非常適合這種情況,特別是如果您不想創建鏈接這兩個對象的構造函數。 – 2010-03-17 14:08:56

0

也許這是過於簡單,但什麼阻止你從

UserProfile profile = new UserProfile(); 
profile.Name = UserModel[0].Name; 
profile.OtherProperty = UserModel[0].OtherProperty; 
... 
DataServices.Save(profile); 

如果它是一個封裝問題,你不能修改這些屬性,然後羅布的有關創建一個構造函數用戶對象的回答聽起來很合適。

+0

感謝您的回答。我唯一擔心的是桌子上有很多領域,所以如果有一些簡單的方法可以做到這一點,那將更容易和更清潔。 – developer 2010-03-17 15:39:09

+0

在這種情況下,每當我更改表中的字段時,我都必須去編輯代碼。有沒有什麼辦法可以使用Reflections來實現這個目標? – developer 2010-03-17 16:21:24

+0

@developer,你看過Rob的回答嗎,我沒有看過AutoMapper,但Chad和Rob似乎都認爲它適合你。 – 2010-03-17 16:26:39

2

也許我不完全理解你的要求。但是,如果你有兩個表,如

DataTable user; 
DataTable userProfiles; 

而你要的UserProfiles包含相同的字段(或者說相同的列)作爲Table可以使用

userProfiles= user.Clone(); // This will copy the schema of user table 
userProfiles= user.Copy(); // This will copy the schema AND data of user table 

現在,如果你想在某些複製行然後你可以做到以下幾點。

DataRow dr; 
userProfiles= user.Clone(); // Do this first to create the schema. 
foreach(DataRow row in user.Rows) 
{ 
    if(...) // code to determine if you want to add this row 
    { 
     userProfiles.Rows.Add(row); // This will add the same row from user table to userProfiles; Or you could create a new row using the 'dr' above and copy the data to provide a new DataRow 
    } 
} 
相關問題