dapper:使用QueryMultiple同时获取结果和计数

时间:2016-06-08 11:37:24

标签: c# sql .net sql-server dapper

我编写了两段SQL命令,想要在一个查询中处理如下:

SELECT COUNT(*) FROM books

SELECT * FROM books ORDER BY bookID OFFSET 1000 ROWS FETCH NEXT 10 ROWS ONLY

如何使用conn.QueryMultiple方法同时获取countlist of books

不过:顺便说一句:我不想创建任何额外的实体类

2 个答案:

答案 0 :(得分:8)

来自github example

var sql = @"SELECT COUNT(*) FROM books
            SELECT * FROM books ORDER BY bookID OFFSET 1000 ROWS FETCH NEXT 10 ROWS ONLY";

using(var multi = connection.QueryMultiple(sql))
{
    var count = multi.Read<int>().Single();
    var results = multi.Read<YourObject>().ToList();
}

答案 1 :(得分:1)

为了更好的表现

var sql=@"SELECT *,count(*) over() as AllCount
FROM Books ORDER BY BookId OFFSET 1000 ROWS FETCH NEXT 10 ROWS ONLY"

var result = result = dbConnection.Query<Book, int, Tuple<Book, int>>(sql, Tuple.Create, splitOn:"AllCount").ToList();
var count = result.Select(c => c.Item2).FirstOrDefault();
List<Book> list = result.Select(c => c.Item1).ToList();