Dapper 可以批处理一组存储过程调用吗?

发布于 2024-11-30 09:26:38 字数 147 浏览 0 评论 0原文

Dapper 可以批量处理一组存储过程调用吗?我在文档中看到它支持多个结果,但我不确定是否可以使用 Dapper 执行多个存储过程调用。

Can Dapper batch a set of stored proc calls? I see it supports Multiple Results in the documentation but I'm not sure if you can execute multiple stored proc calls using Dapper.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鼻尖触碰 2024-12-07 09:26:38

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);

上面的代码重复使用 IDbCommand 和文本 #spInsert 3 次。这使得批量插入更加高效。

一般来说,如果您担心此级别的性能,您会将批处理调用包装在事务中。

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

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

这将导致插入三行。

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

Dapper supports batching commands for stored procs:

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);

The code above reuses the IDbCommand with the text #spInsert, 3 times. This makes batching inserts a bit more efficient.

In general if you worry about perf at this level you would wrap the batch call in a transaction.

Additionally Dapper supports whatever batch you decide to send it:

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

Which would cause three rows to be inserted.

Further more, if #spInsert returned a result set you could use QueryMultiple to execute the batch which would give you 3 record sets to iterate through.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文