LINQ to Entities分组

时间:2017-06-07 21:41:25

标签: c# sql linq

我编写了以下SQL查询,说明了我要实现的目标:

SELECT
    K.id,
    SUM(BP.pris)
FROM Kunde K
JOIN Booking BO ON K.id = BO.Kunde_id
JOIN Bane_Booking BB ON BO.id = BB.Booking_id
JOIN Banepris BP ON BO.starttid = BP.time
WHERE BO.gratis = 0
GROUP BY K.id;

基本上它正在检索客户的总支出。现在我正在尝试将此查询转换为LINQ,因为我在我的应用程序中使用LINQ to Entities。这就是我到目前为止所做的:

from kunde in context.Kunde
join booking in context.Booking on kunde equals booking.Kunde
join banepris in context.Banepris on booking.starttid equals banepris.time
from baneBooking in booking.Bane
select new { Kunde = kunde, Booking = booking, BaneBooking = baneBooking, Banepris = banepris };

然而,我希望能够在相同的LINQ查询中对这些进行分组,因此我不必在之后手动对它们进行分组。我将如何实现这一目标?

我需要获得“kunde” - 对象和“banepris.pris”的总和。

1 个答案:

答案 0 :(得分:2)

没有你的数据库,我无法对此进行测试,但这应该是关闭的:

from K in context.Kunde
join BO in context.Booking on K.id equals BO.Kunde_id
join BP  in context.Banepris on BO.starttid equals BP.time
where BO.gratis == 0
group new { Kunde = K, Pris = BP.pris } by K.id into g
select new { ID=g.Key, Kunde = g.First().Kunde, Sum = g.Sum(k=>k.Pris)}