developer
developer

Reputation: 5478

Copy one object to another

I have 2 tables, user and userprofile. The userprofile 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?

Upvotes: 1

Views: 1224

Answers (3)

galford13x
galford13x

Reputation: 2531

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

Upvotes: 2

Nathan Koop
Nathan Koop

Reputation: 25197

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.

Upvotes: 0

Rob Packwood
Rob Packwood

Reputation: 3798

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.

Upvotes: 4

Related Questions