You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC中含CASE、SUM的分组查询LINQ无法翻译报错如何解决

问题原因
  • 你使用的EF Core版本对GroupBy后聚合函数内直接访问关联导航属性n.Member.Sector的表达式支持不足,无法将其转换为对应SQL的CASE语句
  • 多余的Include调用无需添加,聚合查询不需要加载完整关联实体,反而会提升翻译失败的概率
修复方案

先将查询需要的字段投影为扁平化的匿名类,消除导航属性层级后再进行分组聚合,EF Core即可正常翻译为你需要的带CASE判断和SUM聚合的SQL语句:

var registerBySectorByDate = await _context.HealthRegistration
    .Where(m => m.RegisterDateTime >= fromDate && m.RegisterDateTime <= toDate)
    // 扁平化投影所需字段,消除导航属性层级
    .Select(m => new 
    {
        RegisterDate = m.RegisterDateTime.Date,
        Sector = m.Member.Sector
    })
    .GroupBy(m => m.RegisterDate)
    .Select(g => new
    {
        RegisterDate = g.Key,
        AdministradorCount = g.Sum(x => x.Sector == Member.Sectors.Administrador ? 1 : 0),
        AlunoCount = g.Sum(x => x.Sector == Member.Sectors.Aluno ? 1 : 0),
        ProfessorCount = g.Sum(x => x.Sector == Member.Sectors.Professor ? 1 : 0),
        FuncionarioCount = g.Sum(x => x.Sector == Member.Sectors.Funcionario ? 1 : 0)
    })
    .ToListAsync();

如果使用的EF Core版本过旧仍无法翻译,可以在Where方法后追加AsEnumerable()将数据加载到内存再进行后续分组聚合操作,仅适合数据量较小的场景。

内容的提问来源于stack exchange,提问作者Felipe K. Bernardino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:36:01