问题
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.
回答1:
Once you have a session
, you could
var criteria = session.CreateCriteria(....)
int count = (int) criteria.UniqueResult();
回答2:
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.
来源:https://stackoverflow.com/questions/8047600/nhibernate-count-rows-in-subquery