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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19337468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:47:27  来源:igfitidea点击:

Multiple SQL statements in one roundtrip using Dapper.NET

c#sql.netsql-serverdapper

提问by user1224129

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 中是否有类似的功能?

回答by Steve

Yes, the Dapper QueryMultipleextension can do that:

是的,DapperQueryMultiple扩展可以做到这一点:

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 Gravellthis is the ideal way to execute multiple queries in a single batch.

根据Marc Gravell 的说法,这是在单个批处理中执行多个查询的理想方式。

Note: Dapper creator Sam Saffronhas posted a detailed explanation with code sampleon using QueryMultipleto accomplish this.

注意:Dapper 创建者Sam Saffron已经发布了一个详细的解释和代码示例QueryMultiple用于完成此操作。

回答by Ahmad Aghazadeh

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