单个查询中的 EF 多个聚合

发布于 2024-10-01 16:08:30 字数 270 浏览 3 评论 0原文

我想根据不同的条件获取一组的计数:

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

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

I want to get count of a set based on different condition:

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

How its possible to call all three queries in one DB round trip to increase performance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉城 2024-10-08 16:08:30

当然,只需将您的三个计数包装在 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();           
}

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

Sure, just wrap up your three counts in a POCO or anonymous type:

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

Also, dispose your context, as I show.

凝望流年 2024-10-08 16:08:30

要聚合任意子查询,请使用虚拟单行结果集,从中嵌套所需的子查询。假设 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() };

To aggregate arbitrary subqueries, use a dummy single-row result set from which you nest the desired subqueries. Assuming db represents your DbContext, the code to count invoice types will look like this:

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

If the want to generically get a count of all types, use grouping:

var counts =
    from i in db.Invoices
    group i by i.Type into g
    select new { Type = g.Key, Count = g.Count() };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文