【问题标题】:EF Core GroupBy with Select Distinct Count具有选择不同计数的 EF Core GroupBy
【发布时间】:2020-09-04 13:44:36
【问题描述】:

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

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

在 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 =&gt; i.Field).Distinct().Count() 选项,但这似乎在这里不起作用。还有其他建议吗?

谢谢!

【问题讨论】:

  • 开放的 GitHub 问题是github.com/dotnet/efcore/issues/17376。与 EF Core 一样,您需要等待 (?!)。
  • 这似乎是确切的问题。感谢您的链接。我翻了翻,我猜我也在观望营……

标签: c# postgresql linq entity-framework-core


【解决方案1】:

目前,EF Core 不支持组内的任何类型的区分(例如 ElementSelector 中的 ElementSelectorGroupBy 中的 GroupByGroupBy 中的另一个 GroupBy)。如果你在这种情况下坚持使用EF,你必须在内存中获取一些数据:

var result = (await _context.Items
              .Select(p => new { p.ParentAId, p.ParentBId })
              .Distinct()
              .ToListAsync())  // When EF supports mentioned cases above, you can remove this line!
              .GroupBy(i => i.ParentBId, i => i.ParentAId)
              .ToDictionary(g => g.Key, g => g.Distinct().Count());

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2021-11-16
    • 1970-01-01
    • 2020-08-22
    • 2020-10-15
    • 2021-06-18
    • 2021-10-10
    • 2019-03-06
    • 2020-11-05
    相关资源
    最近更新 更多