c# - Sum(with Coalesce) with Group By in linq (for EF6)

标签 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,但我很想知道这应该如何组合在一起。我现在只能勉强理解我的两个。

感谢您的帮助。

最佳答案

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

关于c# - Sum(with Coalesce) with Group By in linq (for EF6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27978022/

相关文章:

c# - 如何用 LINQ 替换嵌套循环 - 以一种干净、可管理的方式

C# linq group by 在同一实体中的不同键上

c# - C# 中的 DLL C++ 等效项(关键字 "IN")

SQL DB2 - WHERE 子句中的条件逻辑

linq - Linq 查询结果的返回数据类型

mysql - 是否可以在 MySQL 表上执行内联 GROUP BY?

sql - oracle中的CHECK约束,用于列之间的值检查

c# - 用具体实现 C# 替换基类

c# - WPF:ComboBox 中的多种前景色

c# - 有没有办法在不使用端点的情况下从 Identity Server 中生成访问 token ?