If I had a User model that looks like this:
public class User
{
public Guid Id { get; set; }
public DateTime CreatedAtUtc { get; set; }
public string Username { get; set; }
public string Country { get; set; }
}
...and I'd perform a query which starts at a given row and fetches a limited amount of further rows (basically for paginating over the results) that looks like this:
var spaniards = connection.Query<User>(
"select * from Users where Country=@Country OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY",
new { Country = "Spain" }).ToList();
.. using Dapper(.Net), would it be possible to get that particular, limited result set AND the total count of rows in one single query and if so.. how?
答案 0 :(得分:0)
解决此问题的一种方法是使用splitOn功能,以及count(1)over()
我们假设以下sql字符串:
var sql = "select *, overall_count = COUNT(1) OVER() from Users ORDER BY Id Asc OFFSET 5 ROWS;"
以及以下dapper.net电话:
HashSet<int> hashSet = new HashSet<int>();
Func<User, int, User> map = (result, count) =>
{
hashSet.Add(count);
return result;
};
await connection.QueryAsync(sql, map, "overall_count").ConfigureAwait(false);
这会将dapper调用的结果分成两部分(就像加入不同的表一样)并且每次都会调用map functor,在这种情况下我们只是将计数存储在一个hashset中(然后你可以检查一下hashSet.Count是1)
希望这有帮助
PS:我不确定您的OFFSET是否在没有任何ORDER BY的情况下工作