简体   繁体   中英

Sum(with Coalesce) with Group By in linq (for EF6)

I have the following SQL that I would like to write as a single linq statement:

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

The best I can do is use two sets of linq queries, like so:

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

I don't care if it's a method chain or a lambda but I would love to know how this is supposed to go together. I can only barely understand the two I've got now.

Thanks for the help.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM