mscommunity.net

Interactive mscommunity.net online activities
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.

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.

Published ožu 31 2009, 03:05 by boris.sevo
Filed under:

Comments

 

anonymous said:

Thank you man ... you did save me a lot of time ... PEACE . :)

listopad 5, 2009 9:14
 

anonymous said:

Thank you for sharing. Your post helped me before I could have spent a good amount of time figuring out the issue.

studeni 6, 2009 12:54
 

anonymous said:

Thanks sooo much, your post helped enormously !

ožujak 5, 2010 11:02
 

anonymous said:

I'm another one you saved! Yeah!

kolovoz 5, 2010 9:51
 

anonymous said:

MANY MANY thanks, saved my hell time...........

rujan 1, 2010 4:03

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server (Commercial Edition), by Telligent Systems