【问题标题】:How to implement pagination with group by using Entity Framework Core 3.0 without retrieving all rows?如何在不检索所有行的情况下使用 Entity Framework Core 3.0 实现分组分页?
【发布时间】:2021-10-03 16:26:14
【问题描述】:

当需要首先对输入数据进行分组时,您将如何实现分页?我通过以下链接了解如何实现分页:

LINQ and pagination

,但我希望能够做到这一点,其中分页列表中的每个项目都是来自输入数据的一个组(可以扩展)。类似于下面的代码 - 为了防止将表的所有行检索到内存中,ordersList 是IQueryable。返回的IQueryable 是我想传递给分页函数的内容。

from order in ordersList
group order by order.FullName into customers
select customers

但是,这样的查询在客户端上运行(实际上在 Entity Framework Core 3.0+ 中会引发异常)。对于这种情况,有没有办法只检索当前页面上的项目?

【问题讨论】:

    标签: c# linq group-by linq-to-entities entity-framework-core-3.0


    【解决方案1】:

    您必须检索有限的数据,然后在客户端进行分组:

    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;
    
    

    【讨论】:

      【解决方案2】:

      您必须按组分页。您应该使用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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        • 2021-08-23
        • 2017-07-29
        • 2020-02-25
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多