[英]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
不支持组内的任何类型的区别(例如GroupBy
的ElementSelector
内的Distinct
或GroupBy
的ElementSelector
内的另一个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.