在我的ASP.NET MVC项目中,我试图实现相当于这个SQL Server代码:
SELECT COUNT(*) as TotalCount, SUM(SomeColumn) as TotalSum
FROM SomeTable
WHERE param1 = 'foo' AND param2 = 'bar'
...在单个异步查询中使用Entity Framework。基本上我不仅要求总和,还要在一次调用中获得用于计算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端创建一个视图或存储过程吗?
答案 0 :(得分:3)
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();
我在正在运行的开发环境中测试了同步版本。
答案 1 :(得分:0)
确实没有必要在IQueryable上调用SumAsync。以下内容将以您希望的方式为您提供所需的查询:
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();