c# - EF : Avoiding multiple update statements

标签 c# entity-framework ef-code-first

代码如下:

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/

相关文章:

entity-framework - 如何在代码优先的多对多关系中指定关系名称

c# - 如何打印出树结构?

c# - 串行端口。 BytesToRead() 函数

c# - 如何在 Linq 连接期间设置 x.foo = y?

.net - 从存储过程创建 Entity Framework 对象

entity-framework - EF 7 - 导航属性 - SQL 不正确?

c# - XmlElement 和 XmlNodeList 的隐式转换问题

c# - 如何在 bot 框架 v4 中将对话框设置为欢迎消息

c# - 如何使用 C#-WPF-Entity-Framework Code First 应用程序创建数据库备份?

c# - 如何从映射中忽略嵌套枚举