实体框架多次使用单个查询计数

时间:2012-01-17 12:34:47

标签: c# asp.net-mvc-3 entity-framework entity-framework-4

很抱歉,如果有人问这个问题,但是如何通过一次调用数据库来改进以下内容?

var statsModel = new
{
     Total = _db.Messages.Count(),
     Approved = _db.Messages.Count(x => x.Approved),
     Rejected = _db.Messages.Count(x => !x.Approved),
};

3 个答案:

答案 0 :(得分:6)

这可能会有所帮助:

var statsModel =(
        from message in _db.Messages
        group message by 1 into g
        select new
        {
            Total = g.Count(),
            Approved =g.Count (x =>x.Approved),
            Rejected =g.Count (x =>!x.Approved)
        }
    ).FirstOrDefault();

答案 1 :(得分:5)

首先,您可以按照总计和接受度计算Rejected

Rejected = Total - Approved

为了进一步改进,你可以一次性计算它们;

from m in _db.Messages
let Total =  _db.Messages.Count()
let Accept = _db.Messages.Count(x => x.Approved == true)
select new {Total , Accept})

<强>更新 现在简单的黑客攻击:只需要第一行

(from m in _db.Messages
let Total =  _db.Messages.Count()
let Accept = _db.Messages.Count(x => x.Approved == true)
select new {Total , Accept}).Take(1);

但我正在寻找一个更清洁的人

答案 2 :(得分:0)

在C#中(而不是LINQ查询中),异步语法:

var statsModel = await _db.Messages
.GroupBy(m => 1, (g, mm) => new
{
    Total = mm.Count(),
    Approved = mm.Count(m => m.Approved),
    Rejected = mm.Count(m => !m.Approved)
})
.SingleAsync();