This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
Beware when querying a one-to-many collection (bag, set, map, list, etc) with the LINQ standard operators Any() or Count() (or even with the collection’s own Count property: if the collection is mapped as lazy = true, it will be loaded entirely from the DB (if it is not already loaded). That is because the Any() and Count() methods are from LINQ to Objects, not LINQ to NHibernate:
There are two possible solutions:
- Map the collection with lazy = extra and use the collection's Count property;
- Perform an independent query (not on the collection) to find if the association has any elements: