2
votes

Is there a way of dynamically setting the loading strategy between two entities at load time?

For example if I have a Parent entity that has a list of Child entities, I may want to load the 'Parent' entity with lazy loaded children in some situations and eager loading in others.

Is there a way to do this? The mapping seems to imply its one or the other.

1

1 Answers

8
votes

Yes the suggested strategy is to default your entities to use lazy loading, and then when you want to eager load them you change your Query and specify that you want your children to be loaded eagerly.

As to how you actually implement the eager loading, it depends on what query style you're using. (i.e. Linq2NH, Criteria, HQL)

For example, with Linq2NH I believe it's something like this:

session.Query<Parent>().Fetch(p => p.Child)...

With HQL you would use

fetch

Like this:

from Parent as p left join fetch p.Child...

and finally, with the Criteria API, you would do something like this:

var criteria = context.Session.CreateCriteria<Parent>();
criteria.SetFetchMode("Child", NHibernate.FetchMode.Eager);
....