繁体   English   中英

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();
}

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

Microsoft.EntityFrameworkCore.dll中发生类型'System.Data.SqlClient.SqlException'的异常,但未在用户代码中处理

和输出

Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler:Error:迭代查询结果时数据库中发生异常。 System.Data.SqlClient.SqlException:无法对包含聚合或子查询的表达式执行聚合功能。

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

坏消息是,当前(v.1.1.0)EF Core LINQ查询翻译/处理仍然是一场噩梦。 经过大量的试验和错误之后,从EF Core基础结构中获取了不正确的SQL(因此有SQL异常)或不同的内部异常,我唯一能够通过单个SQL获得所需结果且没有异常的方法如下(必须完全以这种方式编写):

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);

当然,由于使用导航属性不起作用,所以我猜了一些名称,如果需要,可以将其替换为您的名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM