EFCore 3 GroupBy+ToDictionary 引发不支持客户端 GroupBy

EFCore 3 GroupBy+ToDictionary raises client side GroupBy is not supported

无法翻译以下 GroupBy 查询并将引发错误:client side GroupBy is not supported

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 之后,应该有一个 Select 语句,它仅使用 Group Key(及其属性)和聚合。这类似于 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);

这会翻译成功。