Search code examples
c#asp.net-mvcentity-frameworkasp.net-mvc-5

Include both COUNT(*) and Sum(X) in a single async query Entity Framework


In my ASP.NET MVC project I'm trying to achieve the equivalent of this SQL Server code:

SELECT COUNT(*) as TotalCount, SUM(SomeColumn) as TotalSum 
FROM SomeTable
WHERE param1 = 'foo' AND param2 = 'bar'

...with Entity Framework in a single async query. Essentially I'm looking to get not only the sum, but also the number of rows used to calculate the sum of the SomeColumn column in a single call.

So far I've only managed to do this in two calls:

using (var context = new myEntities())
{
    // 1st query which does .SumAsync(x => x.SomeColumn)
    // 2nd query which performs a .Count() on the result set
}

Is it possible to do this in one async call, like the SQL provided above? Should I just create a view or stored proc on the SQL side?


Solution

  •  var query = await (from zz in db.SomeTable
                           where zz.Foo > 1
                           group zz by 1 into grp
                           select new
                           {
                               rowCount = grp.CountAsync(),
                               rowSum = grp.SumAsync(x => x.SomeColumn)
                           }).ToListAsync();
    

    I tested a sync version in a dev environment I am running.