【问题标题】:EF Core - How to group by a nullable column through multiple joinsEF Core - 如何通过多个连接按可空列分组
【发布时间】:2020-04-18 01:54:33
【问题描述】:

鉴于 EF Core 2.2 中的以下模型:

public class A
{
    public int Id { get; set; }
    public ICollection<B> Bs { get; set; }
}

public class B
{
    public int Id { get; set; }
    public int AId { get; set; }
    public ICollection<C> Cs { get; set; }
}

public class C
{
    public int Id { get; set; }
    public int BId { get; set; }
    public long? DId { get; set; }
}

public class D
{
    public long Id { get; set; }
}

我想执行这个查询:

from a in context.Set<A>()
from b in a.Bs
from c in b.Cs
where c.DId.HasValue
group c by c.DId.Value into g
select new
{
    g.Key,
    Count = g.Count() - 1
}

但是当我尝试执行此操作时,我得到:

无法翻译 LINQ 表达式“GroupBy(Convert([b.Cs].DId, Int64), [b.Cs])”,将在本地计算。

我参考了这些:

但我似乎无法正确编写查询。这在 EF Core 2.2 上可行吗?或者有没有更好的方法来获得我正在寻找的结果?

【问题讨论】:

    标签: c# linq entity-framework-core ef-core-2.2


    【解决方案1】:

    您编写查询的方式没有任何问题。这只是 EF Core 2.2 查询翻译错误/缺陷之一,因为按c.DId 分组有效,位结果键类型为long?。同样在 EF Core 3.1 中,查询可以正确翻译。

    2.2 的解决方法是使用中间匿名类型对您执行可空到不可空“转换”的键进行分组。像这样的:

    group c by new { Value = c.DId.Value } into g
    select new
    {
        Key = g.Key.Value,
        Count = g.Count() - 1
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 2021-11-16
      • 2021-01-14
      • 2020-01-21
      相关资源
      最近更新 更多