开发者

Copy one object to another

开发者 https://www.devze.com 2022-12-22 22:58 出处:网络
I have 2 tables, user and userprofile. The use开发者_如何学运维rprofile table has a lot of fields similar to the user table. What I need to do is, on click of a button I need to copy all the fields of

I have 2 tables, user and userprofile. The use开发者_如何学运维rprofile table has a lot of fields similar to the user table. What I need to do is, on click of a button I need to copy all the fields of user table to userprofile table.

How can I do that?


Can you create a constructor on UserProfile that takes a User instance as a parameter and do it there? Not sure that is the best approach or if that violates good design. There is a utility called AutoMapper out there that is good at inferring links between two seemingly unrelated objects, you may want to check that out because it is pretty cool.


Perhaps I'm not fully understanding your request. But if you have two tables such as

DataTable user;
DataTable userProfiles;

And you want userProfiles to contain the same fields (or rather same columns) as table1 you can use

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

Now if you want to copy on certain rows then you could do the following.

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


Perhaps this is overly simplistic, but what's stopping you from

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

If it's an encapsulation issue and you can't modify those properties, then Rob's answer about creating a constructor that takes a User object sounds appropriate.

0

精彩评论

暂无评论...
验证码 换一张
取 消