Development With A Dot

Blog on development in general, and specifically on .NET



My Friends

My Links

Permanent Posts

Portuguese Communities

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 = :id").SetParameter("id", 100).UniqueResult<Order>();
In LINQ, there is the Fetch, ThenFetch, FetchMany and ThenFetchMany operators:

   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.

Bookmark and Share


Adam said:


Nhibernate dosen't ignore the loading strategies, he moves them in time.

If you set LazyLoading on true in your relation, and then retrieve entity using linq provider, provider takes

only main entity, but Session object knows that main entity has child with LazyLoading attribute set on true, and then immediately invoke sql to retrieve child entity.

All happens because:

Lazy-Loading - tells when load entities - this's move in time

Fetch - how gets entities - it's can be ignore with hql and linq providers

# July 11, 2011 3:10 AM

Ricardo Peres said:


What I mean, if you prefer is: NHibernate treats every associated entity and relation as lazy.

# July 11, 2011 4:57 AM

adam said:

@Ricardo Peres

Yes, lazy is default configuration, but I think it's nice to say in this entry that nhibernate dosen't ignore loading strategies if we turn LazyLoading on.

This's only my opinion.

# July 11, 2011 4:36 PM

Caelyn said:

Haha, shouldn't you be chrgaing for that kind of knowledge?!

# September 27, 2011 9:49 AM