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

asp.net-core-1.0 c# entity-framework-core

Question

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.

1
2
12/1/2016 5:23:25 PM

Accepted Answer

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.

4
12/1/2016 8:48:29 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow