简体   繁体   English

使用 Dapper.NET 在一次往返中执行多个 SQL 语句

[英]Multiple SQL statements in one roundtrip using Dapper.NET

There is a nice feature in ADO.NET that allows you to send multiple SQL statements to database in one roundtrip and receive results for all statements: ADO.NET 中有一个很好的功能,它允许您在一次往返中将多个 SQL 语句发送到数据库并接收所有语句的结果:

var command = new SqlCommand("SELECT count(*) FROM TableA; SELECT count(*) FROM TableB;", connection);

using(var reader = command.ExecuteReader())
{
    reader.Read();
    resultA = reader.GetInt32(0);
    reader.NextResult();
    reader.Read();
    resultB = reader.GetInt32(0);
}

Is there a similar feature in Dapper.NET? Dapper.NET 中是否有类似的功能?

Yes, the Dapper QueryMultiple extension can do that:是的,Dapper QueryMultiple扩展可以做到这一点:

string query = @"SELECT COUNT(*) FROM TABLEA;
                 SELECT COUNT(*) FROM TABLEB";
using (var multi = connection.QueryMultiple(query, null))
{
    int countA = multi.Read<int>().Single();
    int countB = multi.Read<int>().Single();
}     

According to Marc Gravell this is the ideal way to execute multiple queries in a single batch.根据Marc Gravell 的说法,这是在单个批处理中执行多个查询的理想方式。

Note: Dapper creator Sam Saffron has posted a detailed explanation with code sample on using QueryMultiple to accomplish this.注意:Dapper 创建者Sam Saffron发布了关于使用QueryMultiple完成此操作的代码示例详细说明

UPDATE: I add the important comment from Marc更新:我添加了 Marc 的重要评论

Note: from 1.5-ish (a little earler on the alpha builds) there is a ReadSingle() method that may be more convenient and efficient than Read().Single()注意:从 1.5-ish(alpha 版本的早期版本)有一个 ReadSingle() 方法可能比 Read().Single() 更方便和有效

var grid = connection.QueryMultiple("
             SELECT COUNT(*) FROM TABLEA
             SELECT COUNT(*) FROM TABLEB
             SELECT COUNT(*) FROM TABLEC");
var lstResult = new List<int>();
var isNext = false;
do{
    var first2 = info.Read<int>().Single();
    lstResult.Add(first2);
    isNext=info.IsConsumed;
}
while (!isNext);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM