如何在不检索所有行的情况下使用 Entity Framework Core 3.0 实现分组分页?
How to implement pagination with group by using Entity Framework Core 3.0 without retrieving all rows?
当输入数据需要先分组时,你会如何实现分页?我从下面的 link 了解如何实现分页:
LINQ and pagination
,但我希望能够做到这一点,其中分页列表中的每个项目都是来自输入数据的一个组(可以扩展)。类似于下面的代码——为了防止将 table 的所有行检索到内存中,ordersList 是 IQueryable
。返回的 IQueryable
是我想传递给分页函数的内容。
from order in ordersList
group order by order.FullName into customers
select customers
然而,这样的查询在客户端上运行(实际上在 Entity Framework Core 3.0+ 中抛出异常)。对于这种情况,有没有办法只检索当前页面上的项目?
您必须按组分页。您应该使用 group number
而不是 page number
。
//group sequence
int groupSeq = 1;
//select current group
var p = (from order in context.TBLGroups
group order by order.FullName into customers
select customers.Key).OrderBy(a => a).Skip(groupSeq - 1).Take(1).FirstOrDefault();
string FullName = p.ToString();
//get all items in current group
var items = (from order in context.TBLGroups
where order.FullName == FullName
select order).ToList();
您必须检索有限的数据,然后在客户端分组:
var keys = ordersList
.Select(o => new {o.FullName})
.Distinct()
.OrderBy(о => o.FullName)
.Skip(pageNumber * pageSize)
.Take(pageSize);
var items =
from order in ordersList
join key in keys on order.FullName equals key.FullName
select order;
var result =
from order in items.AsEnumerable()
group order by order.FullName into customers
select customers;
当输入数据需要先分组时,你会如何实现分页?我从下面的 link 了解如何实现分页:
LINQ and pagination
,但我希望能够做到这一点,其中分页列表中的每个项目都是来自输入数据的一个组(可以扩展)。类似于下面的代码——为了防止将 table 的所有行检索到内存中,ordersList 是 IQueryable
。返回的 IQueryable
是我想传递给分页函数的内容。
from order in ordersList
group order by order.FullName into customers
select customers
然而,这样的查询在客户端上运行(实际上在 Entity Framework Core 3.0+ 中抛出异常)。对于这种情况,有没有办法只检索当前页面上的项目?
您必须按组分页。您应该使用 group number
而不是 page number
。
//group sequence
int groupSeq = 1;
//select current group
var p = (from order in context.TBLGroups
group order by order.FullName into customers
select customers.Key).OrderBy(a => a).Skip(groupSeq - 1).Take(1).FirstOrDefault();
string FullName = p.ToString();
//get all items in current group
var items = (from order in context.TBLGroups
where order.FullName == FullName
select order).ToList();
您必须检索有限的数据,然后在客户端分组:
var keys = ordersList
.Select(o => new {o.FullName})
.Distinct()
.OrderBy(о => o.FullName)
.Skip(pageNumber * pageSize)
.Take(pageSize);
var items =
from order in ordersList
join key in keys on order.FullName equals key.FullName
select order;
var result =
from order in items.AsEnumerable()
group order by order.FullName into customers
select customers;