无法翻译以下 GroupBy
查询并将引发错误:不支持客户端 GroupBy
IEnumerable<int> ids = new List<int> { 1, 2, 3 };
var q = db.Comments.Where(x => ids.Contains(x.Identifier))
.GroupBy(x => x.Identifier);
var map = await q.ToDictionaryAsync(x => x.Key, x => x.Count());
应该如何重新安排查询才能在 dbms 上运行?
最佳答案
在任何 group by 之后,应该有一个仅使用 Group Key(及其属性)和聚合的 Select 语句。这类似于 Sql
语言中的限制。作为一种优化,EF 核心团队可能会支持调用具有相同限制的 ToDictionary
,但他们没有,所以我们需要手动执行此操作:
IEnumerable<int> ids = new List<int> { 1, 2, 3 };
var q = db.Comments.Where(x => ids.Contains(x.Identifier))
.GroupBy(x => x.Identifier)
.Select(x => new { x.Key, Count = x.Count()});
var map = await q.ToDictionaryAsync(x => x.Key, x => x.Count);
这将被成功翻译。
关于c# - EFCore 3 GroupBy+ToDictionary 引发不支持客户端 GroupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59331835/