简体   繁体   English

强制实体框架在一次往返中更新几条记录。

[英]Force Entity Framework to update several records in one round trip.

I have to update multiple records in EF and I've come up with the following two methods: 我必须在EF中更新多个记录,并且提出了以下两种方法:

Method 1: ExecuteSqlCommand (direct SQL) 方法1: ExecuteSqlCommand (直接SQL)

customDB.Database.ExecuteSqlCommand(
@"UPDATE  dbo.UserInfo
SET     dbo.UserInfo.Email = dbo.IAMUser.Email,
        dbo.UserInfo.Mobile = dbo.IAMUser.Phone
FROM    dbo.UserInfo
        INNER JOIN dbo.IAMUserMapping ON dbo.UserInfo.UserID = dbo.IAMUserMapping.fUserId
        INNER JOIN dbo.IAMUser ON IAMUser.IAMID = IAMUserMapping.fIAMID
WHERE   dbo.IAMUser.IAMID = @iamid ", new SqlParameter("@iamid", SqlDbType.UniqueIdentifier) { Value = IAMID });

Method 2: Linq foreach: 方法2:Linq foreach:

var ui = from userInfo in customDB.UserInfo
     join userMapping in customDB.IAMUserMapping 
         on userInfo.UserID equals userMapping.fUserId
     join iamUser in customDB.IAMUser 
         on userMapping.IAMUser.IAMID equals iamUser.IAMID
     where iamUser.IAMID == IAMID
     select new
     {
         userInfo.UserID,
         iamUser.Email,
         iamUser.Phone
     };

foreach (var x1 in ui)
{
    var u = new UserInfo
    {
        UserID = x1.UserID,
        Email = x1.Email,
        Mobile = x1.Phone
    };
    customDB.UserInfo.Attach(u);
    var entry = customDB.Entry(u);
    entry.Property(e => e.Email).IsModified = true;
    entry.Property(e => e.Mobile).IsModified = true;
}
customDB.SaveChanges();

Method #1 is the most efficient, resulting in a single SQL query. 方法1是最有效的,导致单个SQL查询。

Method #2 is as efficient on the SQL Server side of things, but it generates a lot more round trips to the server. 方法2在SQL Server方面同样有效,但是它会产生到服务器的更多往返。 1 select to get the records, then 1 update for each record that is updated. 1选择获取记录,然后为每个更新的记录更新1。

Method #2 will give a compile time error if anything in the DB is changed, while #1 will give a run time error. 如果更改了数据库中的任何内容,则方法2将给出编译时错误,而方法1将给出运行时错误。

What do people consider the best practice in cases like these? 在这种情况下,人们认为最佳做法是什么?

Is there any way to get the best of both worlds? 有什么办法可以做到两全其美吗?

With first approach problems that you may faced will be much more critical and harder to solve, eg when renaming/restructuring of entities. 对于第一种方法,您可能面临的问题将变得更加关键和难以解决,例如在重命名/重组实体时。 Compile time errors are much better, easy to solve then runtime ones. 编译时错误要好得多,比运行时的错误更容易解决。

Also, I am not sure how ExecuteSqlCommand method works, but looks like this code is vulnerable to SQL Injection. 另外,我不确定ExecuteSqlCommand方法的工作方式,但看起来此代码容易受到SQL注入的攻击。 So, I will definitelly choose linq approach. 因此,我将绝对选择linq方法。

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

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