将一个对象复制到另一个

时间:2010-03-16 20:47:06

标签: c# .net wpf

我有2个表,user和userprofile。 userprofile表有许多类似于用户表的字段。我需要做的是,点击一个按钮,我需要将用户表的所有字段复制到userprofile表。

How can I do that?

3 个答案:

答案 0 :(得分:4)

您可以在UserProfile上创建一个构造函数,该构造函数将User实例作为参数并在那里执行吗?不确定这是最好的方法还是违反了良好的设计。有一个名为AutoMapper的实用程序,它擅长推断两个看似无关的对象之间的链接,你可能想要检查它,因为它非常酷。

答案 1 :(得分:2)

也许我没有完全理解你的要求。但是如果你有两个表,比如

DataTable user;
DataTable userProfiles;

并且您希望userProfiles包含与您可以使用的table1相同的字段(或相同的列)

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
   }
}

答案 2 :(得分:0)

也许这过于简单化,但是什么阻止了你

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

如果这是一个封装问题并且您无法修改这些属性,那么Rob的回答是关于创建一个使User对象听起来合适的构造函数。