简体   繁体   中英

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:

Method 1: ExecuteSqlCommand (direct 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:

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.

Method #2 is as efficient on the SQL Server side of things, but it generates a lot more round trips to the server. 1 select to get the records, then 1 update for each record that is updated.

Method #2 will give a compile time error if anything in the DB is changed, while #1 will give a run time error.

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. So, I will definitelly choose linq approach.

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.

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