Error: NHibernate.LazyInitializationException was unhandled by user code


When using Fluent Nhibernate I have encountered several times the following exception:

NHibernate.LazyInitializationException was unhandled by user code

In my situation, the error was showing up when I try to get details from a referenced  column. For instance, from a movies table I have several columns, one of which was CategoryID. In my details view, I wanted to display CategoryName rather than CategoryId so my code looked similar to:

string Category = movie.Category.Name.toString();

That’s when the error was coming up stating that the session was closed. However, when using:

string Category = movie.Category.Id.toString();


The last example when I was getting the Id, the error was not fired since the CategoryId is within the same table and thus the session would be open. However, when attempting to get the Category Name, the session would be closed since that session was opened specifically for the movie table.


To solve this I simply modified a line of code in my mapping class where I was adding the reference and added the fetch join:


Id(x => x.Id);

References<Category>(x => x.CategoryId, “CategoryId”);


Id(x => x.Id);

References<Category>(x => x.CategoryId, “CategoryId”).Fetch.Join();