Rich Andrews
Rich Andrews

Reputation: 4188

NHibernate Linq Group By fails to group properly in SQL Server

I have the following LINQ query which uses NHibernate against a SQL Server backed repository...

var casesByCaseOwner = this.preGrantDetailRepository.All
   .Where(x => x.CaseFileLocation.Id == cflId)
   .GroupBy(x => x.CaseOwner)
   .Select(x => new StagSummaryForCfItem
   {
      Id = x.Key.Id,
      Description = x.Key.Name,
      NumberOfCases = x.Count(),
      UninvoicedNetFee = x.Sum(y => y.UninvoicedNetFee),
      UninvoicedDisbursement = x.Sum(y => y.UninvoicedDisbursement)
   }).AsEnumerable();

However, it complains that SQL Server is unable to group by the CaseOwner.Name column because it is not contained in the select list or group clause. Coming from a database world I understand that error, however, I'm not sure how to force NHibernate to group by both Id and Name but still have the CaseOwner entity available to me in my Select.

Upvotes: 11

Views: 3276

Answers (1)

Rich Andrews
Rich Andrews

Reputation: 4188

I found the answer finally...

     var casesByCaseOwner = this.preGrantDetailRepository.All
     .Where(x => x.CaseFileLocation.Id == cflId)
     .GroupBy(x => new { x.CaseOwner.Id, x.CaseOwner.Name })
     .Select(x => new StagSummaryForCfItem
     {
        Id = x.Key.Id,
        Description = x.Key.Name,
        NumberOfCases = x.Count(),
        UninvoicedNetFee = x.Sum(y => y.UninvoicedNetFee),
        UninvoicedDisbursement = x.Sum(y => y.UninvoicedDisbursement)
     }).AsEnumerable();

     return casesByCaseOwner;

This works nicley, it turns out I need to project a new entity with the properties I want to group on.

Upvotes: 7

Related Questions