Sql – ordering by collection count in nhibernate

collectionsnhibernatesql-order-by

Is there a way of ordering a list of objects by a count of a property which is a collection?

For arguments sake let's say I have a question object with a question name property, a property that is a collection of answer objects and another property that is a collection of user objects. The users join the question table via foreign key on question table and answers are joined with middle joining table.

If I want nhibernate to get a list of "question" objects could I order it by
Question.Answers.Count?

i've tried the documentation's example using HQL:

 List<Question> list = nhelper.NHibernateSession
        .CreateQuery("Select q from Question q left join q.Answers a group by q,a order by count(a)")
        .List<Question>();

but i get

"column Question.Name is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" 

I've tried adding all the properties to the group by list but it doesn't work. What happens then is that foreign key userId causes the same error as above but i can't include it in the group by as nhibernate lists it as

Question.Users.UserId

which doesn't solve it if included.

any ideas?

Best Answer

I ran into this issue and I used Linq to get around it.

            var sort = from n in c
                       orderby q.Answers.Count
                       select n;

I BELIEVE that's the syntax, if someone could verify that would be great I haven't used LINQ too much.

Related Topic