简体   繁体   中英

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

This is my complete method, in the call of this method I get an exception

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

and output

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.

The good news are that the problem is not in your (absolutely valid) LINQ query.

The bad news are that currently (v.1.1.0) EF Core LINQ query translation/processing is still a total nightmare. After a lot of trial and error, getting either incorrect SQL (hence SQL exceptions) or different internal exceptions from EF Core infrastructure, the only(!) way I was able to get the desired result with single SQL and no exceptions is as follows (must be written exactly this way):

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

Of course since using navigation property doesn't work, I guessed some names, you can replace them with yours if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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