Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 290
Felipe Zaniol Avatar asked Mar 10 '23 12:03

Felipe Zaniol


1 Answers

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.

like image 127
Ivan Stoev Avatar answered Mar 25 '23 16:03

Ivan Stoev