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?