使用Dapper.NET一次往返多个SQL语句
在ADO.NET中有一个很好的function,允许您在一个往返中将多个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中是否有类似的function?
是的,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的创build者Sam Saffron已经发布了关于使用QueryMultiple
完成这个代码示例的详细解释 。
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);