EF Core LINQ查询由于限制而失败?

时间:2019-11-17 07:20:02

标签: c# entity-framework ef-core-3.0

我正在尝试对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行令人担忧。也许我的分组和汇总已结束。

1 个答案:

答案 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]