【问题标题】:orderby not working before groupby in entity framework coreorderby 在实体框架核心中的 groupby 之前不起作用
【发布时间】:2023-02-05 21:23:01
【问题描述】:

我想订购用户,然后按 GroupCode 分组并获得组的第一项 我必须使用take,因为用户数量很大 我使用这段代码,它工作正常但 OrderBy 不工​​作。

public class User
{
    public int Id { get; set; }
    public int GroupCode { get; set; }
    public DateTime CreatedDateTime { get; set; }
}
var query = _context.Users
    .OrderByDescending(s => s.CreatedDateTime)
    .GroupBy(s => s.GroupCode)
    .Select(g => g.First())
    .Take(10)
    .ToListAsync()

【问题讨论】:

标签: c# entity-framework asp.net-core entity-framework-core


【解决方案1】:

EF Core 将查询转换为 SQL,并且在 SQL 中 ORDER BY 不能位于 GROUP BY 之前。

您可以在 LINQ-to-Objects 中执行此操作,所以。 documentation 说:

IGrouping<TKey,TElement> 对象的生成顺序基于生成每个 IGrouping<TKey,TElement> 的第一个键的源中元素的顺序。分组中的元素按照生成它们的元素在源中出现的顺序生成。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
相关资源
最近更新 更多