简体   繁体   English

EFCore - Select 分组后

[英]EFCore - Select After Group By

List<int> data = dbContext.table
.GroupBy(x => x.Date)
.OrderByDescending(x => x.Key)
.Take(1)
.SelectMany(x => x.Select(c => c.Id))
.ToList();

With this query, i want to get all ids with the latest date.通过此查询,我想获取所有具有最新日期的 ID。 But I get an error for this query using EFCore.(But this works just fine using EF not EFCore).但是我在使用 EFCore 时遇到此查询的错误。(但使用 EF 而不是 EFCore 时效果很好)。 Error says;错误说;

"The LINQ expression... could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'." “LINQ 表达式...无法翻译。以可以翻译的形式重写查询,或者通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估’”

I am curious why it works in Ef but not EFCore?我很好奇为什么它在 Ef 中有效但在 EFCore 中无效?

In SQL a GROUP BY clause collapses rows and returns a single row per group.在 SQL 中,GROUP BY 子句折叠行并为每个组返回一行。 That row can only contain the group columns and aggregate rows.该行只能包含组列和聚合行。 .SelectMany(x => x.Select(c => c.Id)) doesn't make sense in a GROUP BY query. .SelectMany(x => x.Select(c => c.Id))在 GROUP BY 查询中没有意义。

I suspect the query is trying to retrieve the IDs for the latest date.我怀疑查询正在尝试检索最新日期的 ID。 In SQL that requires a subquery to find that latest date:在 SQL 中,需要一个子查询来查找最新日期:

SELECT ID
FROM TheTable
Where Date=(SELECT MAX(Date) 
            FROM TheTable)

The equivalent in EF would be: EF 中的等价物是:

var ids=dbContext.TheTable
                 .Where(t=>t.Date==dbContext.TheTable.Max(r=>r.Date))
                 .Select(t=>t.Id)
                 .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM