Search code examples
linqcountentity-framework-6having

SQL query with Group By and Having Clause in LINQ structure


how do I write this query in LINQ (c# EF6)?

Can someone please help me here - I am new to Entity Framework Structure - So bit hard for me to use different clauses

SELECT 
    sum(remainingamount) TotalSiteCreditAmount,
    max(expirationutcdatetime) MaxExpiryDate
FROM 
    WholesaleCredits
WHERE 
    ExpirationUTCDateTime > Getdate()
GROUP BY 
    registeredcustomerid,
    siteid
HAVING 
    registeredcustomerid = :registeredCustomerId
    AND siteid = :siteId

Tried below thing as of now :

var data =  context.WholesaleCredit
                .Where(x => x.ExpirationUTCDateTime > DateTime.Now)
                .GroupBy (x => x.RegisteredCustomerId)

Entity Used in code:

 public partial class WholesaleCredits
    {
        public virtual int Id { get; set; }
        public virtual decimal CreditAmount { get; set; }
        public virtual decimal RemainingAmount { get; set; }
        public virtual Site Site { get; set; }
        public virtual DateTime GeneratedUTCDateTime { get; set; }
        public virtual DateTime ExpirationUTCDateTime { get; set; }
        public virtual int RegisteredCustomerId { get; set; }
    }

Solution

  • You do not need HAVING here and Grouping should be provided by constant, because you have filter on grouping keys:

    var data = context.WholesaleCredit
        .Where(x => x.ExpirationUTCDateTime > DateTime.Now && x.RegisteredCustomerId == registeredCustomerId && x.Site.Id == siteid)
        .GroupBy(x => 1)
        .Select(g => new 
        {
            TotalSiteCreditAmount = g.Sum(x => x.RemainingAmount),
            MaxExpiryDate = g.Max(x => x.ExpirationUTCDateTime)
        })
        .First();