How do I get row count using the NHibernate QueryOver api?

Jim Geurts picture Jim Geurts · Mar 22, 2010 · Viewed 20.3k times · Source

I'm using the QueryOver api that is part of NHibernate 3.x. I would like to get a row count, but the method I'm using returns all objects and then gets the count of the collection. Is there a way to just return an integer/long value of the number of rows?

I'm currently using:

_session.QueryOver<MyObject>().Future().Count()

Answer

Jim Geurts picture Jim Geurts · Mar 22, 2010

After a bit of playing around with the api, this will do it:

_session.QueryOver<MyObject>()
    .Select(Projections.RowCount())
    .FutureValue<int>()
    .Value

If you don't want to return it as a future, you can just get the SingleOrDefault<int>() instead.