将嵌套的T-SQL选择查询转换为linq

时间:2018-12-01 10:48:45

标签: entity-framework linq

我有以下SQL查询,正尝试将其转换为LINQ查询:

python

1 个答案:

答案 0 :(得分:0)

我使用以下代码解决了该问题:

 var pay = from p in db.BillPayments
                      group p by new { p.BillId } into g

                      select new
                      {
                          payKey = g.Key,
                          TotalPayments = g.Sum(p => p.PaymentAmount)

                      };


 var query = from c in db.Customers
                            join b in db.Bills on c.Id equals b.CustomerId
                            join p in pay on b.Id equals p.payKey.BillId into cs
                            from xx in cs.DefaultIfEmpty()

                            group new { c, b, xx } by new { c.Name, c.MobilePhone, c.Id, c.CustomerCode } into g

                            select new
                            {
                                Received = g.Key,

                                TotalPayment = g.Sum(p => p.xx.TotalPayments == null ? 0 : p.xx.TotalPayments),
                                TotlalBilling = g.Sum(p => p.b.BillAmount),

                                GrandTotal = g.Sum(p => p.b.BillAmount) - g.Sum(p => p.xx.TotalPayments == null ? 0 : p.xx.TotalPayments)


                            };