how to concert SQL query to LINQ with count , group by and isnull clause











up vote
0
down vote

favorite












I have the following SQL Query which I am trying to translate to LINQ Query



SELECT C.NAME,C.MOBILEPHONE,ISNULL (SUM(P.PAYMENTAMOUNT),0)  AS 
PAYAMOUNT,BILLAMOUNT ,B.ID,BILLNO , BILLDATE FROM CUSTOMERS C
JOIN BILLS B ON B.CUSTOMERID=C.ID
LEFT JOIN BILLPAYMENTS P ON P.BILLID=B.ID
GROUP BY C.NAME ,B.BILLAMOUNT,B.ID,BILLNO,BILLDATE,C.MOBILEPHONE
HAVING B.BILLAMOUNT> ( ISNULL(SUM(P.PAYMENTAMOUNT),0))


How do you represent this in LINQ ?



I have seen the typical implementation this



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

group xx by new { c.Name, c.MobilePhone, b.BillAmount, b.BillNo, b.Id, b.BillDate } into g
where g.Sum(p => p.PaymentAmount) < g.Key.BillAmount
select new
{
Received = g.Key,
ReceivedTotal = g.Sum(p => p.PaymentAmount)

};


but am unsure how to implement the following :



 HAVING B.BILLAMOUNT> ( ISNULL(SUM(P.PAYMENTAMOUNT),0)) 









share|improve this question






















  • HAVING clause is basically the same as WHERE clause, but only used with GROUP BY clause.
    – JohnB
    Nov 20 at 5:56










  • reading: old.devkimchi.com/2014/09/02/…
    – JohnB
    Nov 20 at 5:57















up vote
0
down vote

favorite












I have the following SQL Query which I am trying to translate to LINQ Query



SELECT C.NAME,C.MOBILEPHONE,ISNULL (SUM(P.PAYMENTAMOUNT),0)  AS 
PAYAMOUNT,BILLAMOUNT ,B.ID,BILLNO , BILLDATE FROM CUSTOMERS C
JOIN BILLS B ON B.CUSTOMERID=C.ID
LEFT JOIN BILLPAYMENTS P ON P.BILLID=B.ID
GROUP BY C.NAME ,B.BILLAMOUNT,B.ID,BILLNO,BILLDATE,C.MOBILEPHONE
HAVING B.BILLAMOUNT> ( ISNULL(SUM(P.PAYMENTAMOUNT),0))


How do you represent this in LINQ ?



I have seen the typical implementation this



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

group xx by new { c.Name, c.MobilePhone, b.BillAmount, b.BillNo, b.Id, b.BillDate } into g
where g.Sum(p => p.PaymentAmount) < g.Key.BillAmount
select new
{
Received = g.Key,
ReceivedTotal = g.Sum(p => p.PaymentAmount)

};


but am unsure how to implement the following :



 HAVING B.BILLAMOUNT> ( ISNULL(SUM(P.PAYMENTAMOUNT),0)) 









share|improve this question






















  • HAVING clause is basically the same as WHERE clause, but only used with GROUP BY clause.
    – JohnB
    Nov 20 at 5:56










  • reading: old.devkimchi.com/2014/09/02/…
    – JohnB
    Nov 20 at 5:57













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have the following SQL Query which I am trying to translate to LINQ Query



SELECT C.NAME,C.MOBILEPHONE,ISNULL (SUM(P.PAYMENTAMOUNT),0)  AS 
PAYAMOUNT,BILLAMOUNT ,B.ID,BILLNO , BILLDATE FROM CUSTOMERS C
JOIN BILLS B ON B.CUSTOMERID=C.ID
LEFT JOIN BILLPAYMENTS P ON P.BILLID=B.ID
GROUP BY C.NAME ,B.BILLAMOUNT,B.ID,BILLNO,BILLDATE,C.MOBILEPHONE
HAVING B.BILLAMOUNT> ( ISNULL(SUM(P.PAYMENTAMOUNT),0))


How do you represent this in LINQ ?



I have seen the typical implementation this



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

group xx by new { c.Name, c.MobilePhone, b.BillAmount, b.BillNo, b.Id, b.BillDate } into g
where g.Sum(p => p.PaymentAmount) < g.Key.BillAmount
select new
{
Received = g.Key,
ReceivedTotal = g.Sum(p => p.PaymentAmount)

};


but am unsure how to implement the following :



 HAVING B.BILLAMOUNT> ( ISNULL(SUM(P.PAYMENTAMOUNT),0)) 









share|improve this question













I have the following SQL Query which I am trying to translate to LINQ Query



SELECT C.NAME,C.MOBILEPHONE,ISNULL (SUM(P.PAYMENTAMOUNT),0)  AS 
PAYAMOUNT,BILLAMOUNT ,B.ID,BILLNO , BILLDATE FROM CUSTOMERS C
JOIN BILLS B ON B.CUSTOMERID=C.ID
LEFT JOIN BILLPAYMENTS P ON P.BILLID=B.ID
GROUP BY C.NAME ,B.BILLAMOUNT,B.ID,BILLNO,BILLDATE,C.MOBILEPHONE
HAVING B.BILLAMOUNT> ( ISNULL(SUM(P.PAYMENTAMOUNT),0))


How do you represent this in LINQ ?



I have seen the typical implementation this



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

group xx by new { c.Name, c.MobilePhone, b.BillAmount, b.BillNo, b.Id, b.BillDate } into g
where g.Sum(p => p.PaymentAmount) < g.Key.BillAmount
select new
{
Received = g.Key,
ReceivedTotal = g.Sum(p => p.PaymentAmount)

};


but am unsure how to implement the following :



 HAVING B.BILLAMOUNT> ( ISNULL(SUM(P.PAYMENTAMOUNT),0)) 






entity-framework linq sql-to-linq-conversion






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 5:33









Amir Mohammad Firoozi

12




12












  • HAVING clause is basically the same as WHERE clause, but only used with GROUP BY clause.
    – JohnB
    Nov 20 at 5:56










  • reading: old.devkimchi.com/2014/09/02/…
    – JohnB
    Nov 20 at 5:57


















  • HAVING clause is basically the same as WHERE clause, but only used with GROUP BY clause.
    – JohnB
    Nov 20 at 5:56










  • reading: old.devkimchi.com/2014/09/02/…
    – JohnB
    Nov 20 at 5:57
















HAVING clause is basically the same as WHERE clause, but only used with GROUP BY clause.
– JohnB
Nov 20 at 5:56




HAVING clause is basically the same as WHERE clause, but only used with GROUP BY clause.
– JohnB
Nov 20 at 5:56












reading: old.devkimchi.com/2014/09/02/…
– JohnB
Nov 20 at 5:57




reading: old.devkimchi.com/2014/09/02/…
– JohnB
Nov 20 at 5:57












1 Answer
1






active

oldest

votes

















up vote
0
down vote













So you have a sequence of Customers, where every Customer has zero or more Bills, and every Bill belongs to exactly one Customer: a straightforward one-to-many relation.



Furthermore, every Bill has zero or more BillPayments, where every BillPayment belongs to exactly one Bill, also a one-to-many relation.



Alas you forgot to tell us your classes. If you followed the entity framework code first conventions, you'll have something similar to:



class Customer
{
public int Id {get; set;}
public string Name {get; set;}
...

// every Customer has zero or more Bills (one-to-many)
public virtual ICollection<Bill> Bills {get; set;}
}
class Bill
{
public int Id {get; set;}
public int BillNo {get; set;}
public decimal BillAmount {get; set;}
...

// every Bill belongs to exactly one Customer, using foreign key
public int CustomerId {get; set;}
public virtual Customer Customer {get; set;}

// every Bill has zero or more BillPayments (one-to-many)
public virtual ICollection<BillPayment> BillPayments {get; set;}
}
class BillPayment
{
public int Id {get; set;}
...

// every BillPayment belongs to exactly one Bill, using foreign key
public int BillId {get; set;}
public virtual Bill Bill{get; set;}

// every Bill has zero or more BillPayments (one-to-many)
public virtual ICollection<BillPayment> BillPayments {get; set;}
}



In entity framework, the columns of your table are represented by non-virtual properties, the virtual properties represent the relations between the tables.




You also forgot the requirements of your query. It seems to me, that you want the following:




Give me certain properties of Bills (Id, BillNo, BillDate, BillAmount), with certain properties of the Customer of this Bill (Name and MobilePhone), of all Bills that are not fully paid yet. Or in other words, of all Bills where the sum of all payments is less than the BillAmount.




One of the nice things about entity framework, is that you don't have to do the joins yourself, you can use the virtual properties. Entity Framework knows the relations between the tables and does the proper joins for you.



Just for fun, we'll add the original BillAmount, the AmountPaid, and the RemainingAmount, so you can tell your Customer how much he still has to pay when you phone him on his mobile phone



In the requirement you see the central role of Bills, so let's use that as starting point:



// (1) from all bills, calculate the AmountPaid; remember the original bill data:
var notFullyPaidBills = myDbContext.Bills
.Select(bill => new
{
BillData = bill,
AmountPaid = bill.BillPayments
.Select(billPayment => billPayment.PaymentAmount)
.Sum(),
})
// (2) Keep only those bills that are not fully paid yet
.Where(bill => bill.Bil.BillAmount > bill.AmountPaid)

// (3) from the remaining bills select the required properties:
.Select(bill => new
{
// Customer properties:
CustomerName = bill.BillData.Customer.Name,
MobilePhone = bill.BillData.Customer.MobilePhone,

// bill properties:
BillId = bill.BillData.Id,
BillNo = bill.BillData.BillNo,
BillDate = bill.BillData.Date,

// Amounts:
BillAmount = bill.BillData.BillAmount,
AmountPaid = bill.AmountPaid,
RemainingAmount = bill.BillData.BillAmount - bill.AmountPaid,
});


See? When using the virtual properties of your entity framework classes, the queries will look much simpler and more intuitive than when you are doing the (group)joins yourself.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386816%2fhow-to-concert-sql-query-to-linq-with-count-group-by-and-isnull-clause%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    So you have a sequence of Customers, where every Customer has zero or more Bills, and every Bill belongs to exactly one Customer: a straightforward one-to-many relation.



    Furthermore, every Bill has zero or more BillPayments, where every BillPayment belongs to exactly one Bill, also a one-to-many relation.



    Alas you forgot to tell us your classes. If you followed the entity framework code first conventions, you'll have something similar to:



    class Customer
    {
    public int Id {get; set;}
    public string Name {get; set;}
    ...

    // every Customer has zero or more Bills (one-to-many)
    public virtual ICollection<Bill> Bills {get; set;}
    }
    class Bill
    {
    public int Id {get; set;}
    public int BillNo {get; set;}
    public decimal BillAmount {get; set;}
    ...

    // every Bill belongs to exactly one Customer, using foreign key
    public int CustomerId {get; set;}
    public virtual Customer Customer {get; set;}

    // every Bill has zero or more BillPayments (one-to-many)
    public virtual ICollection<BillPayment> BillPayments {get; set;}
    }
    class BillPayment
    {
    public int Id {get; set;}
    ...

    // every BillPayment belongs to exactly one Bill, using foreign key
    public int BillId {get; set;}
    public virtual Bill Bill{get; set;}

    // every Bill has zero or more BillPayments (one-to-many)
    public virtual ICollection<BillPayment> BillPayments {get; set;}
    }



    In entity framework, the columns of your table are represented by non-virtual properties, the virtual properties represent the relations between the tables.




    You also forgot the requirements of your query. It seems to me, that you want the following:




    Give me certain properties of Bills (Id, BillNo, BillDate, BillAmount), with certain properties of the Customer of this Bill (Name and MobilePhone), of all Bills that are not fully paid yet. Or in other words, of all Bills where the sum of all payments is less than the BillAmount.




    One of the nice things about entity framework, is that you don't have to do the joins yourself, you can use the virtual properties. Entity Framework knows the relations between the tables and does the proper joins for you.



    Just for fun, we'll add the original BillAmount, the AmountPaid, and the RemainingAmount, so you can tell your Customer how much he still has to pay when you phone him on his mobile phone



    In the requirement you see the central role of Bills, so let's use that as starting point:



    // (1) from all bills, calculate the AmountPaid; remember the original bill data:
    var notFullyPaidBills = myDbContext.Bills
    .Select(bill => new
    {
    BillData = bill,
    AmountPaid = bill.BillPayments
    .Select(billPayment => billPayment.PaymentAmount)
    .Sum(),
    })
    // (2) Keep only those bills that are not fully paid yet
    .Where(bill => bill.Bil.BillAmount > bill.AmountPaid)

    // (3) from the remaining bills select the required properties:
    .Select(bill => new
    {
    // Customer properties:
    CustomerName = bill.BillData.Customer.Name,
    MobilePhone = bill.BillData.Customer.MobilePhone,

    // bill properties:
    BillId = bill.BillData.Id,
    BillNo = bill.BillData.BillNo,
    BillDate = bill.BillData.Date,

    // Amounts:
    BillAmount = bill.BillData.BillAmount,
    AmountPaid = bill.AmountPaid,
    RemainingAmount = bill.BillData.BillAmount - bill.AmountPaid,
    });


    See? When using the virtual properties of your entity framework classes, the queries will look much simpler and more intuitive than when you are doing the (group)joins yourself.






    share|improve this answer

























      up vote
      0
      down vote













      So you have a sequence of Customers, where every Customer has zero or more Bills, and every Bill belongs to exactly one Customer: a straightforward one-to-many relation.



      Furthermore, every Bill has zero or more BillPayments, where every BillPayment belongs to exactly one Bill, also a one-to-many relation.



      Alas you forgot to tell us your classes. If you followed the entity framework code first conventions, you'll have something similar to:



      class Customer
      {
      public int Id {get; set;}
      public string Name {get; set;}
      ...

      // every Customer has zero or more Bills (one-to-many)
      public virtual ICollection<Bill> Bills {get; set;}
      }
      class Bill
      {
      public int Id {get; set;}
      public int BillNo {get; set;}
      public decimal BillAmount {get; set;}
      ...

      // every Bill belongs to exactly one Customer, using foreign key
      public int CustomerId {get; set;}
      public virtual Customer Customer {get; set;}

      // every Bill has zero or more BillPayments (one-to-many)
      public virtual ICollection<BillPayment> BillPayments {get; set;}
      }
      class BillPayment
      {
      public int Id {get; set;}
      ...

      // every BillPayment belongs to exactly one Bill, using foreign key
      public int BillId {get; set;}
      public virtual Bill Bill{get; set;}

      // every Bill has zero or more BillPayments (one-to-many)
      public virtual ICollection<BillPayment> BillPayments {get; set;}
      }



      In entity framework, the columns of your table are represented by non-virtual properties, the virtual properties represent the relations between the tables.




      You also forgot the requirements of your query. It seems to me, that you want the following:




      Give me certain properties of Bills (Id, BillNo, BillDate, BillAmount), with certain properties of the Customer of this Bill (Name and MobilePhone), of all Bills that are not fully paid yet. Or in other words, of all Bills where the sum of all payments is less than the BillAmount.




      One of the nice things about entity framework, is that you don't have to do the joins yourself, you can use the virtual properties. Entity Framework knows the relations between the tables and does the proper joins for you.



      Just for fun, we'll add the original BillAmount, the AmountPaid, and the RemainingAmount, so you can tell your Customer how much he still has to pay when you phone him on his mobile phone



      In the requirement you see the central role of Bills, so let's use that as starting point:



      // (1) from all bills, calculate the AmountPaid; remember the original bill data:
      var notFullyPaidBills = myDbContext.Bills
      .Select(bill => new
      {
      BillData = bill,
      AmountPaid = bill.BillPayments
      .Select(billPayment => billPayment.PaymentAmount)
      .Sum(),
      })
      // (2) Keep only those bills that are not fully paid yet
      .Where(bill => bill.Bil.BillAmount > bill.AmountPaid)

      // (3) from the remaining bills select the required properties:
      .Select(bill => new
      {
      // Customer properties:
      CustomerName = bill.BillData.Customer.Name,
      MobilePhone = bill.BillData.Customer.MobilePhone,

      // bill properties:
      BillId = bill.BillData.Id,
      BillNo = bill.BillData.BillNo,
      BillDate = bill.BillData.Date,

      // Amounts:
      BillAmount = bill.BillData.BillAmount,
      AmountPaid = bill.AmountPaid,
      RemainingAmount = bill.BillData.BillAmount - bill.AmountPaid,
      });


      See? When using the virtual properties of your entity framework classes, the queries will look much simpler and more intuitive than when you are doing the (group)joins yourself.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        So you have a sequence of Customers, where every Customer has zero or more Bills, and every Bill belongs to exactly one Customer: a straightforward one-to-many relation.



        Furthermore, every Bill has zero or more BillPayments, where every BillPayment belongs to exactly one Bill, also a one-to-many relation.



        Alas you forgot to tell us your classes. If you followed the entity framework code first conventions, you'll have something similar to:



        class Customer
        {
        public int Id {get; set;}
        public string Name {get; set;}
        ...

        // every Customer has zero or more Bills (one-to-many)
        public virtual ICollection<Bill> Bills {get; set;}
        }
        class Bill
        {
        public int Id {get; set;}
        public int BillNo {get; set;}
        public decimal BillAmount {get; set;}
        ...

        // every Bill belongs to exactly one Customer, using foreign key
        public int CustomerId {get; set;}
        public virtual Customer Customer {get; set;}

        // every Bill has zero or more BillPayments (one-to-many)
        public virtual ICollection<BillPayment> BillPayments {get; set;}
        }
        class BillPayment
        {
        public int Id {get; set;}
        ...

        // every BillPayment belongs to exactly one Bill, using foreign key
        public int BillId {get; set;}
        public virtual Bill Bill{get; set;}

        // every Bill has zero or more BillPayments (one-to-many)
        public virtual ICollection<BillPayment> BillPayments {get; set;}
        }



        In entity framework, the columns of your table are represented by non-virtual properties, the virtual properties represent the relations between the tables.




        You also forgot the requirements of your query. It seems to me, that you want the following:




        Give me certain properties of Bills (Id, BillNo, BillDate, BillAmount), with certain properties of the Customer of this Bill (Name and MobilePhone), of all Bills that are not fully paid yet. Or in other words, of all Bills where the sum of all payments is less than the BillAmount.




        One of the nice things about entity framework, is that you don't have to do the joins yourself, you can use the virtual properties. Entity Framework knows the relations between the tables and does the proper joins for you.



        Just for fun, we'll add the original BillAmount, the AmountPaid, and the RemainingAmount, so you can tell your Customer how much he still has to pay when you phone him on his mobile phone



        In the requirement you see the central role of Bills, so let's use that as starting point:



        // (1) from all bills, calculate the AmountPaid; remember the original bill data:
        var notFullyPaidBills = myDbContext.Bills
        .Select(bill => new
        {
        BillData = bill,
        AmountPaid = bill.BillPayments
        .Select(billPayment => billPayment.PaymentAmount)
        .Sum(),
        })
        // (2) Keep only those bills that are not fully paid yet
        .Where(bill => bill.Bil.BillAmount > bill.AmountPaid)

        // (3) from the remaining bills select the required properties:
        .Select(bill => new
        {
        // Customer properties:
        CustomerName = bill.BillData.Customer.Name,
        MobilePhone = bill.BillData.Customer.MobilePhone,

        // bill properties:
        BillId = bill.BillData.Id,
        BillNo = bill.BillData.BillNo,
        BillDate = bill.BillData.Date,

        // Amounts:
        BillAmount = bill.BillData.BillAmount,
        AmountPaid = bill.AmountPaid,
        RemainingAmount = bill.BillData.BillAmount - bill.AmountPaid,
        });


        See? When using the virtual properties of your entity framework classes, the queries will look much simpler and more intuitive than when you are doing the (group)joins yourself.






        share|improve this answer












        So you have a sequence of Customers, where every Customer has zero or more Bills, and every Bill belongs to exactly one Customer: a straightforward one-to-many relation.



        Furthermore, every Bill has zero or more BillPayments, where every BillPayment belongs to exactly one Bill, also a one-to-many relation.



        Alas you forgot to tell us your classes. If you followed the entity framework code first conventions, you'll have something similar to:



        class Customer
        {
        public int Id {get; set;}
        public string Name {get; set;}
        ...

        // every Customer has zero or more Bills (one-to-many)
        public virtual ICollection<Bill> Bills {get; set;}
        }
        class Bill
        {
        public int Id {get; set;}
        public int BillNo {get; set;}
        public decimal BillAmount {get; set;}
        ...

        // every Bill belongs to exactly one Customer, using foreign key
        public int CustomerId {get; set;}
        public virtual Customer Customer {get; set;}

        // every Bill has zero or more BillPayments (one-to-many)
        public virtual ICollection<BillPayment> BillPayments {get; set;}
        }
        class BillPayment
        {
        public int Id {get; set;}
        ...

        // every BillPayment belongs to exactly one Bill, using foreign key
        public int BillId {get; set;}
        public virtual Bill Bill{get; set;}

        // every Bill has zero or more BillPayments (one-to-many)
        public virtual ICollection<BillPayment> BillPayments {get; set;}
        }



        In entity framework, the columns of your table are represented by non-virtual properties, the virtual properties represent the relations between the tables.




        You also forgot the requirements of your query. It seems to me, that you want the following:




        Give me certain properties of Bills (Id, BillNo, BillDate, BillAmount), with certain properties of the Customer of this Bill (Name and MobilePhone), of all Bills that are not fully paid yet. Or in other words, of all Bills where the sum of all payments is less than the BillAmount.




        One of the nice things about entity framework, is that you don't have to do the joins yourself, you can use the virtual properties. Entity Framework knows the relations between the tables and does the proper joins for you.



        Just for fun, we'll add the original BillAmount, the AmountPaid, and the RemainingAmount, so you can tell your Customer how much he still has to pay when you phone him on his mobile phone



        In the requirement you see the central role of Bills, so let's use that as starting point:



        // (1) from all bills, calculate the AmountPaid; remember the original bill data:
        var notFullyPaidBills = myDbContext.Bills
        .Select(bill => new
        {
        BillData = bill,
        AmountPaid = bill.BillPayments
        .Select(billPayment => billPayment.PaymentAmount)
        .Sum(),
        })
        // (2) Keep only those bills that are not fully paid yet
        .Where(bill => bill.Bil.BillAmount > bill.AmountPaid)

        // (3) from the remaining bills select the required properties:
        .Select(bill => new
        {
        // Customer properties:
        CustomerName = bill.BillData.Customer.Name,
        MobilePhone = bill.BillData.Customer.MobilePhone,

        // bill properties:
        BillId = bill.BillData.Id,
        BillNo = bill.BillData.BillNo,
        BillDate = bill.BillData.Date,

        // Amounts:
        BillAmount = bill.BillData.BillAmount,
        AmountPaid = bill.AmountPaid,
        RemainingAmount = bill.BillData.BillAmount - bill.AmountPaid,
        });


        See? When using the virtual properties of your entity framework classes, the queries will look much simpler and more intuitive than when you are doing the (group)joins yourself.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 12:43









        Harald Coppoolse

        11.1k12958




        11.1k12958






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386816%2fhow-to-concert-sql-query-to-linq-with-count-group-by-and-isnull-clause%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'