Dapper可以批量处理一组存储的proc调用吗?

Kyl*_*ery 8 .net c# dapper

Dapper可以批量处理一组存储的proc调用吗?我看到它支持文档中的Multiple Results,但我不确定你是否可以使用Dapper执行多个存储过程调用.

Sam*_*ron 10

Dapper支持存储过程的批处理命令:

connection.Execute("create table #t (i int)");
connection.Execute("create proc #spInsert @i int as insert #t values (@i)");
connection.Execute("#spInsert", new[] { new { i = 1 }, new {i = 2}, new {i = 3} }, 
    commandType: CommandType.StoredProcedure);

var nums = connection.Query<int>("select * from #t order by i").ToList();

nums[0].IsEqualTo(1);
nums[1].IsEqualTo(2);
nums[2].IsEqualTo(3);
Run Code Online (Sandbox Code Playgroud)

上面的代码重复使用IDbCommand和文本#spInsert3次.这使得批处理插入更有效.

通常,如果您担心此级别的perf,您可以在事务中包装批处理调用.

此外,Dapper支持您决定发送的任何批次:

connection.Execute(@"
    exec #spInsert @i = @one 
    exec #spInsert @i = @two 
    exec #spInsert @i = @three",
    new { one = 1, two = 2, three = 3 });
Run Code Online (Sandbox Code Playgroud)

这会导致插入三行.

此外,如果#spInsert返回结果集,您可以使用它QueryMultiple来执行批处理,这将为您提供3个记录集以进行迭代.

  • 使用类似的方法将19个过程调用作为一个批次发送而不是单独执行它我的性能提高了约3倍(141s vs 421s).使用StringBuilder从列表中准备查询和@param_i名称,其中i是索引. (2认同)