LINQ to Sql,无法对包含聚合或子查询的表达式执行聚合函数

LINQ to Sql, cannot perform an aggregate function on an expression containing an aggregate or a subquery

private decimal GetBankAccountCashierTotal()
{
    var company = _context.Company.FirstOrDefault();

    return _context.PersonBankAgencyAccount
           .Where(p => p.PersonID.Equals(company.PersonID))
           .Where(c => c.BankAgencyAccountBalance
                .Any(b => b.Reference <= DateTime.Now))
           .Select(x => x.BankAgencyAccountBalance
                .Where(d => d.Reference.Date <= DateTime.Now)
                .OrderByDescending(d => d.Reference)
                .FirstOrDefault()
                .CurrentBalance)
           .sum();
}

这是我的完整方法,在调用这个方法时出现异常

An exception of type 'System.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code

并输出

Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler:Error: An exception occurred in the database while iterating the results of a query. System.Data.SqlClient.SqlException: Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

好消息是问题不在您的(绝对有效的)LINQ 查询中。

坏消息是目前 (v.1.1.0) EF Core LINQ 查询 translation/processing 仍然是一场彻头彻尾的噩梦。经过大量的反复试验,得到不正确的 SQL(因此 SQL 异常)或来自 EF Core 基础结构的不同内部异常,only(!) 方式我能够通过单个 SQL 获得所需的结果并且没有例外如下(必须这样写 exactly):

return _context.PersonBankAgencyAccount
       .Where(p => p.PersonID.Equals(company.PersonID))
       .SelectMany(p => _context.BankAgencyAccountBalance
           .Where(b => b.AccountId == p.Id && b.Reference.Date <= DateTime.Now)
           .OrderByDescending(b => b.Reference)
           .Take(1))
       .Sum(b => b.CurrentBalance);

当然因为使用导航属性不行,我猜了一些名字,有需要的可以换成你自己的