While I was working on some project my goal was to separate all presentation logic from my database access logic and NHibernate API calls so I created facade for creating and disposing NHibernate sessions and querying the database. Everything works fine until I didn't need to display collection of objects in some ListBox control. Suddenly NHibernate's LazyInitializationExceptions started to pop up because my NHibernate session was closed and collection's objects weren't initialized. Because lazy loading is default way of loading collections in NHibernate (which perfectly makes sense because you shouldn't load entities which you don't need) you have 2 ways to prevent above exception's messages to pop up:
- prevent lazy loading in your mapping
- force NHibernate to initialize collection
How can you prevent lazy loading in your mapping depends on the way your mapping is realized. I was using Fluent NHibernate so I did something similar to following code snippet:
public class WorkListMap : ClassMap
HasMany(x => x.Services).Inverse().Not.LazyLoad();
If you wan't to force NHibernate to initialize collection you can call NHibernateUtil.Initialize method.
That's all. I hope this can save you few minutes if you ran into the same problem as I was.