Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 868
Rich Andrews Avatar asked Jan 29 '12 15:01

Rich Andrews


1 Answers

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.

like image 91
Rich Andrews Avatar answered Oct 17 '22 09:10

Rich Andrews