Community Blogs

Blogs of different SQL/Developers Community Members
Signed in as anonymous | Edit Profile | Sign out | Help
in Search

Weblog :: Boris Ševo

Sporadic posts about my interests, e.g. software development (mostly .NET), technology in general and some occasional rant.

ožujak 2009 - Posts

  • NHibernate.LazyInitializationException - failed to lazily initialize a collection, no session or session was closed

    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:

    1. prevent lazy loading in your mapping
    2. 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
    {
    public WorkListMap()
    {
    ...
    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.

Powered by Community Server (Commercial Edition), by Telligent Systems