1

How can I do something like this in nHibernate:

select count(*)
from (subquery)

It is a rather simple query in SQL, but the solution is not so obvious in nHibernate. An obvious solution would be something along the line of:

    var rowcount = Session.QueryOver<Entity>()
       .Select(Projections.Alias(Projections.Count(Projections.SubQuery(detachedQuery)), "count"))
        .FutureValue<int>();

However, this results in an ArgumentOutOfRangeException:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

This SO answer doesn't work for me, as I have a more complex grouping. My question originates from an earlier question where I tried to use ToRowCountQuery, but that function strips groupings form the query.

2 Answers 2

0

Once you have a session, you could

var criteria = session.CreateCriteria(....)

int count = (int) criteria.UniqueResult();
Sign up to request clarification or add additional context in comments.

2 Comments

See stackoverflow.com/questions/116188/… for more info. It is couple of years old, but hope it helps.
Hmmm, I'm not sure how that would work. Where do I put my subquery? The related SO answer doesn't use a subquery, but just provides an alternative solution, which also works in that particular case. The Criteria-solution seems to be similar to my QueryOver solution which results in an exception. Next to that, I would prefer a solution using QueryOver.
0

I found an old post by Ayende which gave me a solution (Counting paged data).

I created my own dialect as described in that post and added the rowcount function to my paged query. And presto, I got my rowcount in a single query to the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.