views:

751

answers:

2

I've just started using NHibernate and fluent-NHibernate which I think is great. I've been configuring all my mappings to use LazyLoading for any relationships between classes because generally I find it isn't neccesary to load everything upfront. However sometimes you know 100% you will be loading all of the relationships or at least one relationship and it will save the extra connection(s) if you get the data up front.

Is there anyway that you can tell NHibernate to load the relationship data for a relationship and override the initial setting?

I was using LinqToSql before, for that I would create repositories which would have an overload of what items should load in which relationships when neccesary. This worked really well so I would like something similar for NHibernate.

+7  A: 

I've found this can be used the LazyLoading / Eager loading feature of NHibernate queries.

Create your ICriteria in the normal manner and then the association name (relationship property, for me is prices) and then the fetch type which can be join, select, lazyload, eager

.SetFetchMode("Prices", FetchMode.Join)
John_
A: 

If you are executing HQL you can use "left outer join fetch" or "left join fetch" to join to the association that you want to be fetched rather than lazy loaded e.g.

If you have a Building class which has a property returning an Address object and this relationship is lazy loaded you may have HQL similar to:

string hql = "from Building bld where bld.Type.Id = 1";

When the Address property is accessed for each building another SQL statement will be executed. Changing the HQL to the following will fetch the addresses as part of the original SQL statement:

string hql = "from Building bld left outer join fetch bld.Address as addr where bld.Type.Id = 1";
Gary Joynes