tags:

views:

125

answers:

3

Hi All,

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?
+4  A: 

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.

Rob Packwood
Automapper is great for this kind of thing, especially if you don't want to create a constructor linking those two objects.
Chad Ruppert
A: 

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.

Nathan Koop
Thanks for the answer. My only concern was that there are a lot of fields in the table, so if there was some simple method out there, which could do it, that would be more easier and cleaner.
developer
In this case I shall have to go and edit the code everytime I change fields in the table. Is there any way I can use Reflections, to achieve this?
developer
@developer, have you looked at Rob's answer, I haven't looked at AutoMapper but both Chad and Rob seem to think it'll work for you.
Nathan Koop
+2  A: 

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