具有选择不同计数的EF核心组

问题描述 投票:0回答:1

我有一张表,Items,它与两个不同的父母有一对多的关系。

我想为每个ParentA选择ParentB的计数。

在SQL中,这很简单:

SELECT "ParentBId", count(distinct "ParentAId") 
FROM "Items"
GROUP BY "ParentBId"

在Linq中,我有此声明:

var itemCounts = await _context.Items
    .GroupBy(item => item.ParentBId,
        (parentBId, items) => new
        {
            ParentBId = parentBId,
            Count = items.Select(item => item.ParentAId).Distinct().Count(),
        }).ToDictionaryAsync(group => group.ParentBId, group => group.Count);

运行此查询时,EF出现此错误:

System.InvalidOperationException: Processing of the LINQ expression 'AsQueryable<string>(Select<Item, string>(
    source: NavigationTreeExpression
        Value: default(IGrouping<string, Item>)
        Expression: (Unhandled parameter: e), 
    selector: (item) => item.ParentAId))' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
   at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
...

[Items表的确按每个层次的表使用带有区分符的列来确定项目类型。我不知道这是否是一个因素。

[我已经看到很多人推荐items.Select(i => i.Field).Distinct().Count()选项,但这似乎在这里不起作用。还有其他建议吗?

谢谢!

c# postgresql linq entity-framework-core
1个回答
0
投票

当前DistinctElementSelector内的GroupBy(以及GroupByElementSelector内的另一个GroupBy)不受支持。如果在这种情况下坚持使用EF Core,则必须获取内存中的一些数据:

EF
© www.soinside.com 2019 - 2024. All rights reserved.