c# - 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() 从数据库中获取数千条记录。
解决方案
试试这个查询:
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();
推荐阅读
- linux - Percona Server MongoDB on Linux - 如何解决与 mongodb-org 的安装冲突?
- c++ - 高效的信号处理
- oracle - Oracle Client 12.2 64bit Pro*C 编译错误 PCC-F-02104 - 无法连接
- angular - 调用 downgradeInjectable 以在 AngularJS 模块中使用新的 Angular 服务会引发 TypeError
- api - Rest API - HTTP Get - 在传递参数方面需要帮助
- spring-boot - Spring Boot:StackOverflowError HttpServletRequestWrapper getUserPrincipal
- c# - 将字节发布到 graphql api
- python - 如何在python中将字符串转换为具有值的数组
- asp.net-mvc - 如何根据Controller中的RoleId调用ajax内的Session?
- bash - 如何在 bash 脚本中以 gb 为单位获取 ram 大小?