Selectively turn off lazy-loading w/NHibernate

fluent-nhibernatenhibernate

With LINQ to Sql, you can specify, for a given fetch, that you don't want specific child elements to be loaded (eagerly or lazily). Is this possible in NHibernate? There are times when I just want the root object and/or only part of the object graph, and I'd like to be able to specify that rather than having to write a DTO and do mapping just to get around the fact that NHibernate feels compelled to load everything if I try to serialize my object.

Thanks!

Best Answer

Yes, but…

The level of flexibility you have here may depend on your version of NHibernate and how you are building your query. For example, a LINQ query (here is where versioning may make a difference) is not going to give you the same flexibility as an ICriteria or HQL query.

With the criteria API, you can call .SetFetchMode(), passing in the property and the desired mode for that query.

NHibernate also allows you to create projections, so you can instantiate objects of unmapped types or DTOs without mapping. Of course, a projection goes only one-way; if it isn't mapped, it can't be persisted.