NHibernate uses criteria for Count (), First ()

I have a question about the Criteria method, the one-to-many relationship to the database, the one to account , the many to sites when I use CreateCriteria() , something is wrong.

Example: SessionFactory.OpenSession().CreateCriteria(typeof(Account)).List().Count();

Before starting, I think SQL should be SELECT COUNT(*) FROM table , but SQL should be SELECT id, siteurl...FROM table . So what's wrong with that? How can I solve it?

And the First() method should be SELECT TOP1 ...FROM table , but this is SELECT ...FROM table

I am an unloved rookie, Please help me.

+4
source share
1 answer

This is because the Count method, which you call at the end, is executed after the query is executed and outside the database. You only count the items in the list in memory. To achieve what you are looking for, you can use the projection:

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

Source: https://habr.com/ru/post/1304548/


All Articles