Я решил это, используя следующий код:
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)
};