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);
}
Dapper.NET中是否有类似的功能?
答案 0 :(得分:85)
是的,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();
}
根据Marc Gravell的说法,这是在一个批次中执行多个查询的理想方式。
注意:Dapper创建者Sam Saffron已使用QueryMultiple
发布detailed explanation with code sample来完成此操作。
答案 1 :(得分:4)
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);