NHibernate use Criteria for Count(),First()

criteria, nhibernate

Solution

This happens because the `Count` method you are calling at the end executes after the query has run and outside of the database. You are only counting the elements in the list in memory. To achieve what you are looking for you could use a projection:

var count = session
    .CreateCriteria<Account>()
    .SetProjection(
        Projections.Count(Projections.Id())
    )
    .UniqueResult<long>();

Problem

I have a question about Criteria method, one-to-many relation to the database, 'one' is "account", 'many' is "sites", when I use `CreateCriteria()` something is not right. Like this: `SessionFactory.OpenSession().CreateCriteria(typeof(Account)).List().Count();` Before it's run, I think the SQL should be `SELECT COUNT(*) FROM table`, but the SQL is `SELECT id, siteurl...FROM table`. So what's wrong with this? How can I solve it? And `First()` method should be `SELECT TOP1 ...FROM table`, but it is `SELECT ...FROM table` I'm an Nhiberate rookie, Please help me.

Original source