How to fix “LazyInitializationException” exception in Nhibernate

When we work with Nhibernate, its fascinating in the beginning . When we actually start using it in real project probably the first problem we fall in is “LazyInitializationException”

Well , Lets take an example (dirty but quick)  here and produce this problem and than fix it.

I have a simple class and it has 2 reference object mapped with(FormulaType and FormulaCategory ).

public MyObjectMap()

{

Id(x => x.Id);

References(x => x.FormulaType);

References(x => x.FormulaCategory);

}

 

Now i want to load MyObject  and try to access reference properties.

using(ISession _session= GetNHBSession())

{

MyObject returnObject  =   _session.Get(obj.Id);

Console.WriteLine(“Formula type Name   “+ returnObject.FormulaType.Value);

}

Code above will raise lazyInintializationException , because reference object is not loaded.

 

Solutions:

(1) One solution is to change the behavior of the mapping of the reference object like mentioned below. Now this reference object will always be loaded.

 

References(x => x.FormulaType).Not.lazyLoad();

References(x => x.FormulaCategory).Not.lazyLoad();

(2)  Nhibernate session covered in using kills the possibility of lazy loading. So change the get  method a little bit and you are done ..


MyObject returnObject  =   _session.Get(obj.Id);

Console.WriteLine(“Formula type Name   “+ returnObject.FormulaType.Value);

 

 


 

Advertisements

3 thoughts on “How to fix “LazyInitializationException” exception in Nhibernate

  1. If some one wishes expert view concerning blogging
    and site-building afterward i propose him/her to pay a
    visit this blog, Keep up the fastidious job.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s