使用列表参数批量 insert/update 调用到单个 operation/request 到 Dapper 中的数据库

Batch insert/update calls with a list parameter into a single operation/request to database in Dapper

基于 Dapper github 页面上的这段代码,我创建了一个批量插入语句。

Dapper 将查询拆分为多个单独的 SQL 插入语句(如 SQL 分析器中所示)。

是否可以指示它将多个操作更改为单个操作以减少 DB 行程的次数,而不必像下面这样手动创建多个插入语句?

insert into test (a,b) values (b,c);
insert into test (a,b) values (d,e);
insert into test (a,b) values (f,g);

Is it possible to instruct it to change multiple operations into a single operation

没有

通常有两个允许执行批量操作的答案:

SqlBulkCopy

正如@iSR5 在评论区的回答:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy

没有比这更快的了。

Dapper Plus

免责声明:我是项目的所有者Dapper Plus

此项目不是免费的,但提供所有批量操作:

  • 批量插入
  • 批量更新
  • 批量删除
  • 批量合并

(在后台使用 SqlBulkCopy

还有一些其他选项,例如输出标识值:

// CONFIGURE & MAP entity
DapperPlusManager.Entity<Order>()
                 .Table("Orders")
                 .Identity(x => x.ID);

// CHAIN & SAVE entity
connection.BulkInsert(orders)
          .AlsoInsert(order => order.Items);
          .Include(x => x.ThenMerge(order => order.Invoice)
                         .AlsoMerge(invoice => invoice.Items))
          .AlsoMerge(x => x.ShippingAddress);   

编辑: 回复评论

SqlBulkCopy can only be used with MS SQL Server though. Isn't it?

确切地说,SqlBulkCopy 仅与 SQL 服务器兼容。我们的图书馆支持多个供应商:

  • SQL 服务器
  • SQL 紧凑
  • 甲骨文
  • MySql
  • PostgreSQL
  • SQL网站
  • 火鸟