无法在分组上翻译 LINQ 表达式

The LINQ expression cannot be translated on Grouping

我有 LINQ 表达式来获取前 15 个最常用的答案

这里是表达式

 var latestAnswers = await _dbContext.TextAnswers.Include(x => x.CompanySurvey).ThenInclude(x => x.Survey)
        .Where(x => x.CompanySurvey.Survey.FiscalYear == 2022)
        .GroupBy(x => x.Answer)
        .OrderByDescending(g => g.Count())
        .Take(15)
        .ToListAsync();

但是我得到这个错误

The LINQ expression 'DbSet() .Include(x => x.CompanySurvey) .ThenInclude(x => x.Survey) .Where(x => x.CompanySurvey.Survey.FiscalYear == (int?)2022) .GroupBy(x => x.Answer) .OrderByDescending(g => g .AsQueryable() .Count()) .Take(__p_0)' 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'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

不明白为什么不能翻译

我该如何解决这个问题?

我这样重写我的代码

 var latestAnswersQuery = await _dbContext.TextAnswers
        .Include(x => x.CompanySurvey).ThenInclude(x => x.Survey)
        .Where(x => x.CompanySurvey.Survey.FiscalYear == 2022)
        .ToListAsync();

    var latestAnswers = latestAnswersQuery.GroupBy(x => x.Answer).OrderByDescending(g => g.Count()).Take(15);
    return latestAnswers;

现在一切都很棒

EF Core 6 必须支持此类查询,但看起来完整的实现支持已移至 EF Core 7

对话后好像不需要从数据库中获取分组记录,只需要分组key和Count

var latestAnswers = await _dbContext.TextAnswers
    .Where(x => x.CompanySurvey.Survey.FiscalYear == 2022)
    .GroupBy(x => x.Answer)
    .Select(g => new { Answer = g.Key, Count = g.Count() })
    .OrderByDescending(x => x.Count)
    .Take(15)
    .ToListAsync();