【发布时间】: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 => i.Field).Distinct().Count() 选项,但这似乎在这里不起作用。还有其他建议吗?
谢谢!
【问题讨论】:
-
开放的 GitHub 问题是github.com/dotnet/efcore/issues/17376。与 EF Core 一样,您需要等待 (?!)。
-
这似乎是确切的问题。感谢您的链接。我翻了翻,我猜我也在观望营……
标签: c# postgresql linq entity-framework-core