简体   繁体   English

在C#实体框架中用另一个实体更新实体

[英]Updating entity with another entity in C# Entity Framework

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? 如何为Geekguy123更新database1,使新的名字为Frederick? The ids are different but the User is unique. 这些ID不同,但用户是唯一的。

To be clear, there are dozens of properties on the entity, which I don't want to update manually. 需要明确的是,实体上有数十个属性,我不想手动更新。 Maybe SQL would be easier? 也许SQL会更容易?

Just query in database 1 for the record you want. 只需在数据库1中查询所需的记录即可。 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. 获取其FirstName属性,然后查询数据库2中的记录,然后使用从数据库1中获得的名字更新firstname字段,然后提交更改。

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. 在这里-您可以使用的传递SQL。

If the table name is really Database1, then replace Table1 , Table2 accordingly. 如果表名称确实是Database1,则相应地替换Table1Table2

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. 我最终删除并使用新值重新添加了实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM