单个查询中的EF多重聚合

时间:2010-11-11 05:22:44

标签: entity-framework aggregate

我想基于不同的条件来计算一组:

 var invoices = new AccountingEntities().Transactions
 var c1 = invoices.Count(i=>i.Type = 0);
 var c2 = invoices.Count(i=>i.Type = 1);
 var c3 = invoices.Count(i=>i.Type = 2);

如何在一次数据库往返中调用所有三个查询以提高性能?

2 个答案:

答案 0 :(得分:7)

当然,只需用POCO或匿名类型包装你的三个计数:

using (var invoices = new AccountingEntities())
{
    var c = (from i in invoices.Transactions
             select new 
             {
                 c1 = invoices.Count(i=>i.Type = 0),
                 c2 = invoices.Count(i=>i.Type = 1),
                 c3 = invoices.Count(i=>i.Type = 2)
             }).Single();           
}

另外,如我所示,处理你的上下文。

答案 1 :(得分:2)

要聚合任意子查询,请使用虚拟单行结果集,从中嵌套所需的子查询。假设db代表您的DbContext,计算发票类型的代码将如下所示:

var counts = (
    from unused in db.Invoices
    select new {
        Count1 = db.Invoices.Count(i => i.Type == 0),
        Count2 = db.Invoices.Count(i => i.Type == 1),
        Count3 = db.Invoices.Count(i => i.Type == 2)
    }).First();

如果要通用获取所有类型的计数,请使用分组:

var counts =
    from i in db.Invoices
    group i by i.Type into g
    select new { Type = g.Key, Count = g.Count() };