Question

I'm trying order a Linq to NHibernate query by the sum of it's children.

session.Linq<Parent>().OrderBy( p => p.Children.Sum( c => c.SomeNumber ) ).ToList()

This does not seem to work. When looking at NHProf, I can see that it is ordering by Parent.Id. I figured that maybe it was returning the results and ordering them outside of SQL, but if I add a .Skip ( 1 ).Take( 1 ) to the Linq query, it still orders by Parent.Id.

I tried doing this with an in memory List and it works just fine.

Am I doing something wrong, or is this an issue with Linq to NHibernate?

I'm sure I could always return the list, then do the operations on them, but that is not an ideal workaround, because I don't want to return all the records.

Was it helpful?

Solution

To order a query by an aggregate value, you need to use a group by query. In your example you need to use a 'group by' with a join.

The equivelant SQL would be something like:

select id, sum(child.parentid) as childsum from dbo.Parent
inner join child on
parent.id= child.parentid 
group by id
order by childsum desc

If only Linq2NH could do this for us... but it can't sadly. You can do it in HQL as long as you're ok with getting the id, and the sum back, but not the whole object.

I battled with Linq2NH for months before I abandoned it. Its slow, doesn't support 2nd level cache and only supports VERY basic queries. (at least when I abandoned it 6 months ago - it may have come along leaps and bounds!) Its fine if you are doing a simple home-made application. If your application is even remotely complex ditch it and spend a bit of time getting to know HQL: a little harder to understand but much more powerful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top