NHibernate Pitfalls: HQL, LINQ and Eager Loading
This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
With the HQL and LINQ query providers, NHibernate ignores the loading strategies specified in the mappings and treats every related entity (many to one, one to one) and collection (one to many, many to many) as lazy. If you want to eagerly load them, you have to tell NHibernate to do it explicitly.
In HQL, it is done using the fetch instruction, together with a join clause:
1: var orders = session.CreateQuery("from Order o join fetch o.Details where o.id = :id").SetParameter("id", 100).UniqueResult<Order>();
1: var orders = session.Query<Order>().Fetch(x => x.Details).Where(x => x.Id == 100).Single();
This is particularly important when using stateless sessions because these do not support lazy loading, so everything must be loaded at the same time.
The Get/Load, Criteria and QueryOver methods do not suffer from this problem.