在我的ASP.NET MVC项目中,我试图实现与以下SQL Server代码等效的功能:

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


...在单个异步查询中使用实体框架。本质上,我不仅希望获得总和,而且还希望获得用于在单个调用中计算SomeColumn列之和的行数。

到目前为止,我只设法通过两个电话做到了这一点:

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


是否可以在一个异步调用中执行此操作,例如上面提供的SQL?我应该只在SQL端上创建视图还是存储proc?

最佳答案

 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();


我在运行的开发环境中测试了同步版本。

关于c# - 在单个异步查询 Entity Framework 中同时包含COUNT(*)和Sum(X),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33115215/

10-12 03:40