首页 > 解决方案 > EF Core 5,在子集合中按日期排序实体

问题描述

我有一个简单的关系,比如

public class Invoice{
  public int Id {get;set;}
  ICollection Product Products {get;set;}
}

public class Product {
  public int Id {get;set;}
  public DateTime ReceptionDate {get;set;}
  public virtual Invoice Invoice{get;set;}
}

我想出示按 Product ReceptionDate 订购的发票,因此最新产品的发票排在最前面。我也在分页结果。

我试过了

invoices.OrderByDescending(x => x.Products.Select(y => y.ReceptionDate)).Skip(x).Take(y);

但这甚至不是一个有效的查询。

通过搜索找不到类似的问题。

谢谢。

编辑:也尝试了 Sergey 解决方案,但它太慢了,因为它调用 ToArray() 从数据库中获取数千条记录。

标签: c#entity-framework.net-coreentity-framework-corefluent

解决方案


试试这个查询:

var query=Products
    .GroupBy(g => new { g.Invoice.Id, g.ReceptionDate})
    .Select(g => new 
        {
           Id=g.Key.Id
           ReceptionDate=g.Key.ReceptionDate
        })
    .OrderBy(x => x.ReceptionDate)
    .ToArray();

推荐阅读