I have a bunch of entities that need to be updated to match entities of the same class in a different database. For example:
Database1 TableA:
Id| User | FirstName| LastName
1 | Geekguy123 | Fred | Smith
Database2 TableA:
Id| User | FirstName| LastName
34| Geekguy123 | Frederick| Smith
How can I update database1 for Geekguy123 so the new FirstName is Frederick? The ids are different but the User is unique.
To be clear, there are dozens of properties on the entity, which I don't want to update manually. Maybe SQL would be easier?
Just query in database 1 for the record you want. Get its FirstName property and then query the record in database 2 and then update firstname field with the one you got from database 1. And then submit your change.
Db1Context c1 = new Db1Context();
var userToUpdateWith = c1.Users.Single(u => u.User == "Geekguy123")
Db2Context c2 = new Db2Context();
var userToUpdate = c2.Users.Single(u => u.User == "Geekguy123")
Since you got to set many properties, you can do the following.
string[] properties = new string[]{"FirstName","LastName"};
foreach(var property in properties){
object value = userToUpdateWith.GetType().GetProperty(property).GetValue(userToUpdateWith, null);
userToUpdate.GetProperty(property).SetValue(userToUpdate, value, null);
c2.SaveChanges();
Here you go - the pass-through SQL that you can use.
If the table name is really Database1, then replace Table1
, Table2
accordingly.
UPDATE t1 SET t1.FirstName = t2.FirstName FROM Database1.dbo.Table1 AS t1 INNER JOIN Database2.dbo.Table2 AS t2 ON t1.User = t2.User
And the passthrough would be like this:
using (var context = new YourDataContext()) { context.Database.ExecuteSqlCommand(sqlString); }
Turns out, there were actually a couple hundred properties. I ended up deleting and re-adding the entity with the new values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.