我正在尝试对EF Core 3.0进行一个简单的分组和求和
但是遇到一个奇怪的错误:
System.InvalidOperationException:'处理LINQ表达式 'AsQueryable(((未处理的参数: y).TransactionLines)”,通过“ NavigationExpandingExpressionVisitor” 失败了这可能表示EF Core中存在错误或限制。
var creditBalances = await context.Transaction
.Include(x => x.TransactionLines)
.Include(x=>x.CreditAccount)
.Where(x => x.CreditAccount.UserAccount.Id == userAccount.Id)
.GroupBy(x => new
{
x.CreditAccount.ExternalId
})
.Select(x => new
{
x.Key.ExternalId,
amount = x.Sum(y => y.TransactionLines.Sum(z => z.Amount))
})
.ToListAsync();
我正在努力寻找可能出现问题的地方,所以甚至不确定从哪里开始。我正在尝试获取所有交易金额的总和(这是每笔交易的所有TransactionLines的总和-即交易金额由与其相关的行组成)。
然后我总结所有交易,然后按CreditAccount ID分组。
Unhandled parameter: y
行令人担忧。也许我的分组和汇总已结束。
答案 0 :(得分:1)
所以从TransactionLines
级别开始,这很简单:
var q = from c in context.TransactionLines
where c.Transaction.CreditAccount.UserAccount.Id == userAccount.Id
group c by c.Transaction.CreditAccount.ExternalId into g
select new
{
ExternalId = g.Key,
Amount = g.Sum(x => x.Amount)
};
var creditBalances = await q.ToListAsync();
(您不需要任何Include()
,因为您没有返回带有相关数据的Entity。您正在投影自定义数据形状。)
翻译为:
SELECT [c].[ExternalId], SUM([t].[Amount]) AS [Amount]
FROM [TransactionLines] AS [t]
LEFT JOIN [Transaction] AS [t0] ON [t].[TransactionId] = [t0].[Id]
LEFT JOIN [CreditAccounts] AS [c] ON [t0].[CreditAccountId] = [c].[Id]
LEFT JOIN [UserAccount] AS [u] ON [c].[UserAccountId] = [u].[Id]
WHERE [u].[Id] = @__userAccount_Id_0
GROUP BY [c].[ExternalId]