我有2個表格,user和userprofile。 userprofile表包含許多類似於用戶表的字段。我需要做的是,點擊一個按鈕,我需要將用戶表的所有字段複製到userprofile表。將一個對象複製到另一個
How can I do that?
我有2個表格,user和userprofile。 userprofile表包含許多類似於用戶表的字段。我需要做的是,點擊一個按鈕,我需要將用戶表的所有字段複製到userprofile表。將一個對象複製到另一個
How can I do that?
您可以創建用戶配置一個構造函數的用戶實例作爲參數,並做到這一點呢?不確定這是最好的方法,還是違反了良好的設計。在那裏有一個名爲AutoMapper的實用程序,它可以很好地推斷兩個看起來不相關的對象之間的鏈接,因此您可能想檢查一下,因爲它非常酷。
Automapper非常適合這種情況,特別是如果您不想創建鏈接這兩個對象的構造函數。 – 2010-03-17 14:08:56
也許這是過於簡單,但什麼阻止你從
UserProfile profile = new UserProfile();
profile.Name = UserModel[0].Name;
profile.OtherProperty = UserModel[0].OtherProperty;
...
DataServices.Save(profile);
如果它是一個封裝問題,你不能修改這些屬性,然後羅布的有關創建一個構造函數用戶對象的回答聽起來很合適。
也許我不完全理解你的要求。但是,如果你有兩個表,如
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
}
}
爲什麼被標記爲WPF問題? – 2010-03-16 22:21:15