一个数据库中的几个汇总操作往返 [英] Several summary operations in one database roundtrip

查看:105
本文介绍了一个数据库中的几个汇总操作往返的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用总摘要的Linq查询的大多数示例是一个返回单个聚合操作的查询。

如何进行多次汇总操作,导致只有一次往返数据库。

例如,我想计算orderdetails的数量(使用某些条件),并且还要计算行数的总和。

Soemthing就像一个SQL查询:

从Orderdetails中选择count(*),sum(price * amount)...

不是我想要做的事情,我想要的比这个例子复杂一点,但只是想知道我需要做什么。要获得这些摘要很简单,但想知道如何通过一次往返数据库来实现它。

Most examples of Linq queries using total summaries is one query returning a single aggregated operation.

How can you have several  summary operations resulting in only one roundtrip to database.

For example I want to count the number of orderdetails (using some conditions) and also make a sum of the amount of row.

Soemthing like an SQL query:

Select count(*), sum(price*amount) from Orderdetails where ...

Not really what I am trying to do, what I want is a bit more complex than this example, but just to get some idea what I need to do. To get those summaries is easy but want to know how I can do it with just one roundtrip to database.

推荐答案

你尝试过这样的事吗?< br>
来自o的context.Orders选择
new {
o.Id
OrderPrice = o.OrderDetails.Sum(od => od.Price * od.Amount),
OrderDetailsCount = o.OrderDetails.Count()
}

Have you tried something like this?

from o in context.Orders select
new {
    o.Id
    OrderPrice = o.OrderDetails.Sum(od => od.Price * od.Amount),
    OrderDetailsCount = o.OrderDetails.Count()
}


这篇关于一个数据库中的几个汇总操作往返的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆