假设我们在 EfCore 中有这些实体......
public class Entity
{
public int Id { get; set; }
public decimal Rate { get; set; }
// ... omitted for brevity
public int? NavigationPropertyId { get; set; }
public NavigationProperty? NavigationProperty { get; set; }
// ... omitted for brevity
}
public class NavigationProperty
{
public int Id { get; set; }
public int AnotherNavigationPropertyId { get; set; }
// ... omitted for brevity
}
...我们希望得到相同的平均值 Rate
。Entities
AnotherNavigationProperty
我尝试的 efcore 查询抛出“System.InvalidOperationException:Nullable 对象必须有一个值”。
from entity in _context.Entities
group entity by entity.NavigationProperty.AnotherNavigationPropertyId
into entitiesByAnotherNavigationProperty
orderby entitiesByAnotherNavigationProperty.Key
select new
{
AnotherNavigationPropertyId = entitiesByAnotherNavigationProperty.Key,
AverageRate = entitiesByAnotherNavigationProperty.Average(a => a.Rate)
}
我知道 EfCoreToQueryString()
在查询返回时已成功翻译
SELECT [p].[AnotherNavigationPropertyId], AVG([a].[Rate]) AS [AverageRate]
FROM [Entities] AS [a]
LEFT JOIN [NavigationProperties] AS [p] ON [a].[NavigationPropertyId] = [p].[Id]
GROUP BY [p].[AnotherNavigationPropertyId]
ORDER BY [p].[AnotherNavigationPropertyId]
在数据库上运行时正确返回我需要的结果
如何提示 EfCore 传播 null 导航属性?(因为表达式树不能包含空传播?.
运算符)