简体   繁体   中英

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?

 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.

It's really not necessary to call SumAsync on the IQueryable. The following will give you the query you want in the way you want it:

            var foo = from item in context.Items
                      group item by item.ID into grp
                      select new
                      {
                          Value = grp.Sum(f => f.ID),
                          Count = grp.Count()
                      };
            await foo.ToListAsync();

Tested with EF Core 6.0

The following LINQ query:

await Table.GroupBy(_ => 1, (_, rows) => new
           {
              Count = rows.Count()
              Sum = rows.Sum(x => x.Column),
              Average = rows.Average(x => x.Column),                  
           })
           .FirstOrDefaultAsync();

Will be translated to the following SQL query:

SELECT TOP(1)
  COUNT(*) AS [Count]
  SUM([t].[Column]) AS [Sum],
  AVG([t].[Column]) AS [Average],     
FROM[Table] AS [t]

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