Set your collection's Lazy loading to Lazy
or Extra
, perhaps yours is set to NoLazy
(a.k.a. eager-loading).
It's better to set it to Extra
instead of Lazy
only. As it will prevent NHibernate from fetching the rows for the child collection when you only want to get the .Count()
or .Any()
of the child collection. Extra
is like a more lazy version of lazy :)
With NoLazy / eager-loading:
var post = session.Get<Post>(1);
That will read one row from post table and row(s) from comments table from the database, even if you didn't access the child collection comments of the post from your application.
Using Lazy
, var post = session.Get<Post>(1)
will only load the one row from posts table, NHibernate will not read the post's child collection comments from the database.
As for the Lazy vs Extra
Using Lazy:
var commentsCount = post.Comments.Count()
That will load the post's comments from the database:
select * from comments where post_id = 1;
And the .Count()
, happens on application-side only.
Using Extra, var commentsCount = post.Comments.Count()
, NHibernate will issue count query only, instead of reading all the rows.
select count(*) from comments where post_id = 1
Here's an example configuration to set the child collection's loading mechanism if you are using NHibernate's automapping, you set that settings on BeforeMapSet event:

And when you need to eager-load the child collection that are configured as Lazy
or Extra
, use FetchMany