单个查询中的 EF 多个聚合
我想根据不同的条件获取一组的计数:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,只需将您的三个计数包装在 POCO 或匿名类型中即可:
另外,如我所示,处理您的上下文。
Sure, just wrap up your three counts in a POCO or anonymous type:
Also, dispose your context, as I show.
要聚合任意子查询,请使用虚拟单行结果集,从中嵌套所需的子查询。假设
db
代表您的 DbContext,计算发票类型的代码将如下所示:如果想要一般性地获取所有类型的计数,请使用分组:
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:If the want to generically get a count of all types, use grouping: