计算分页前记录的总大小,并在分页后返回它们,而无需两次访问数据库

我有一个分页方法,它需要页面和限制,然后将它们应用于给定的集合(可能会应用预过滤器/查询),然后对其应用分页,因此服务器端无需执行任何操作从计数记录到应用分页(仅统计最终结果,该结果无论如何都存储在内存中)

        public async Task<PagingServiceResponse<T>> Apply<T>(IQueryable<T> set)
        {
            var httpQuery = _accessor.HttpContext.Request.Query;
            var pageValue = httpQuery.LastOrDefault(x => x.Key == "page").Value;
            if (pageValue.Count > 0) int.TryParse(pageValue, out _page);
            var limitValue = httpQuery.LastOrDefault(x => x.Key == "limit").Value;
            if (limitValue.Count > 0) int.TryParse(limitValue, out _limit);
            if (_limit > 1000 || _limit <= 0) _limit = 1000;
            if (_page <= 0) _page = 1;
            _size = await set.CountAsync();
            set = set.Take(_limit);
            if (_page > 1) set = set.Skip(_page * _limit);

            var data = await set.ToListAsync();
            var currentSize = data.Count;
            return new PagingServiceResponse<T>
            {
                Data = data,
                Size = _size,
                CurrentSize = currentSize,
                Page = _page,
                PerPage = _limit
            };
        }

So the problem here is that this hits the database twice, to check the total count (CountAsync) and receive the data (ToListAsync)

并且我尝试不执行此操作,因为它执行两次查询(这不是纯查询),因此对其应用了筛选器操作。

如果有其他建议或其他建议,我会全力以赴。

我正在使用PostgreSQL和实体框架核心(npgsql)