簡體   English   中英

EF Core GroupBy 與 Select 不同計數

[英]EF Core GroupBy with Select Distinct Count

我有一張表Items ,它與兩個不同的父母有多對一的關系。

我想ParentA每個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 => i.Field).Distinct().Count()選項,但這似乎在這里不起作用。 還有其他建議嗎?

謝謝!

目前, EF Core不支持組內的任何類型的區別(例如GroupByElementSelector內的DistinctGroupByElementSelector內的另一個GroupBy )。 如果在這種情況下堅持使用EF ,則必須在 memory 中獲取一些數據:

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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM