在linq中使用Group By(使用Coalesce)(对于EF6)

时间:2015-01-16 05:51:04

标签: c# sql linq entity-framework

我想将以下SQL作为单个linq语句编写:

SELECT
     P.PartyId,
     P.PartyDate,
     SUM(COALESCE(R.PaidAmount, 0)) AS AmountPaid
FROM 
     Party AS P 
     LEFT JOIN Reservation as R
          ON P.PartyID = R.PartyID 
GROUP BY P.PartyID, P.PartyDate 
ORDER BY P.PartyDate DESC

我能做的最好的就是使用两组linq查询,如下所示:

var localList = from partyList in localDb.Parties
                join reservationList in localDb.Reservations on
                     partyList.PartyID equals reservationList.PartyID into comboList
                from newList in comboList.DefaultIfEmpty()
                select new PartyAmounts {
                                PartyID = partyList.PartyID,
                                PartyDate = partyList.PartyDate,
                                AmountPaid = (newList.PaidAmount ?? 0) };

var secondList = from groupList in localList
                 group groupList by new {
                                       groupList.PartyID,
                                       groupList.PartyDate} into resList
                 select new PartyAmounts {
                                 PartyID = resList.Key.PartyID,
                                 PartyDate=resList.Key.PartyDate,
                                 AmountPaid = resList.Sum(x => x.AmountPaid)};

我不在乎它是一个方法链还是一个lambda但是我想知道它应该如何组合在一起。我几乎无法理解我现在拥有的两个。

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

var list = from partyList in localDb.Parties
           join reservationList in localDb.Reservations on partyList.PartyID equals reservationList.PartyID into comboList
           from details in comboList.DefaultIfEmpty() // Left join
           group details by new {partyList.PartyID, partyList.PartyDate} into grouped // So that the group have both keys and all items in details
           select new PartyAmounts
           {
             PartyID = grouped.Key.PartyID,
             PartyDate = grouped.Key.PartyDate,
             AmountPaid = grouped.Sum(x => x.AmountPaid ?? 0)}
           };