代码如下:
var compIds = from p in packinglist.List
select p.ComponentId;
var components = from c in context.Components
where compIds.Contains(c.Id)
select c;
foreach (var item in components)
{
item.CurrentSiteId = packinglist.DestinationId;
}
context.SaveChanges();
最终发出大量 SQL 语句,例如
update [dbo].[Components] set [CurrentSiteId] = @0 where ([Id] = @1)
有没有办法指示 EF(Code First)发出以下语句:
update [dbo].[Components] set [CurrentSiteId] = @0 where ([Id] in (....))
或者我应该考虑使用可用的 SQLQuery 方法之一,还是单独的工具,如 Dapper、massive 或 ...?
最佳答案
目前还没有一种方法可以在 EF 4 中执行开箱即用的批量更新。不过,有一些非常漫长、复杂的解决方法最终会生成 SQL。我建议使用存储过程或 T-SQL。下面是我过去使用过的一个快速 T-SQL 片段:
using (var context = new YourEntities())
{
context.ExecuteStoreCommand(
@"UPDATE Components SET CurrentSiteId = 1 WHERE ID IN(1,2,3,4)");
}
关于c# - EF : Avoiding multiple update statements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6959953/