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

4

30

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()
Gard answered 22/3, 2010 at 1:28 Comment(0)
G
45

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.

Gard answered 22/3, 2010 at 17:7 Comment(0)
L
37

Another method

var count = Session.QueryOver<Employer>()
    .Where(x => x.EmployerIsActive)
    .RowCount();
Laugh answered 5/1, 2012 at 11:9 Comment(0)
H
8

Another method:

int employerCount = session
  .QueryOver<Employer>()
  .Where(x => x.EmployerIsActive) // some condition if needed
  .Select(Projections.Count<Employer>(x => x.EmployerId))
  .SingleOrDefault<int>();
Hinrichs answered 8/7, 2011 at 13:14 Comment(0)
H
7

Im using like this:

public int QuantidadeTitulosEmAtraso(Sacado s)
    {
        TituloDesconto titulo = null;
        Sacado sacado = null;

        var titulos =
                _session
                .QueryOver<TituloDesconto>(() => titulo)
                .JoinAlias(() => titulo.Sacado, () => sacado)
                .Where(() => sacado.Id == s.Id)
                .Where(() => titulo.Vencimento <= DateTime.Today)
                .RowCount();

    }
Hospitality answered 27/11, 2012 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.