简体   繁体   English

在单个异步查询实体框架中同时包含 COUNT(*) 和 Sum(X)

[英]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:在我的 ASP.NET MVC 项目中,我试图实现与此 SQL Server 代码等效的代码:

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.本质上,我不仅希望获得总和,还希望获得用于在一次调用中计算SomeColumn列总和的行数。

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?是否可以在一个异步调用中执行此操作,如上面提供的 SQL? Should I just create a view or stored proc on the SQL side?我应该在 SQL 端创建一个视图还是存储过程?

 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. 实际上没有必要在IQueryable上调用SumAsync。 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使用EF Core 6.0测试

The following LINQ query:以下LINQ查询:

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:将转换为以下SQL查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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