EF Core - 如何通过多个连接按可空列分组
EF Core - How to group by a nullable column through multiple joins
给定 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
}
但是当我尝试执行此操作时,我得到:
The LINQ expression 'GroupBy(Convert([b.Cs].DId, Int64), [b.Cs])
' could not be translated and will be evaluated locally.
我参考了这些:
但我似乎无法正确编写查询。这在 EF Core 2.2 上可行吗?或者有没有更好的方法来获得我想要的结果?
您编写查询的方式没有任何问题。它只是 EF Core 2.2 查询翻译之一 bugs/defects,因为 group by c.DId
有效,结果键类型是 long?
。同样在 EF Core 3.1 中,查询可以正确翻译。
2.2 的解决方法是使用中间匿名类型对执行可空到不可空 "conversion" 的键进行分组。像这样:
group c by new { Value = c.DId.Value } into g
select new
{
Key = g.Key.Value,
Count = g.Count() - 1
}
给定 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
}
但是当我尝试执行此操作时,我得到:
The LINQ expression '
GroupBy(Convert([b.Cs].DId, Int64), [b.Cs])
' could not be translated and will be evaluated locally.
我参考了这些:
但我似乎无法正确编写查询。这在 EF Core 2.2 上可行吗?或者有没有更好的方法来获得我想要的结果?
您编写查询的方式没有任何问题。它只是 EF Core 2.2 查询翻译之一 bugs/defects,因为 group by c.DId
有效,结果键类型是 long?
。同样在 EF Core 3.1 中,查询可以正确翻译。
2.2 的解决方法是使用中间匿名类型对执行可空到不可空 "conversion" 的键进行分组。像这样:
group c by new { Value = c.DId.Value } into g
select new
{
Key = g.Key.Value,
Count = g.Count() - 1
}