Sai Stuff to Developers

April 12, 2012

NHIBERNATE: ILLEGAL ATTEMPT TO ASSOCIATE A COLLECTION WITH TWO OPEN SESSIONS

Filed under: DotNet,NHibernate — tosaik @ 4:55 am
Tags: , ,

Hi All recently i got this issue when iam working on my application which is using NHibernate as the OR Mapper, and i seriously work around about this issue and got the tail of this issue.

This issue raised because i get an model object which had lazy load option true and modified the same object and trying to save/update the same object.. this is fine from our side but what accually happening inside the Nhibenate is due to lazy load the model object still running on a Nhibernate session, again when we say save the same object it created another session to save it as current context session is already running to fetch the model object.. so NHibernate doesnt accept an object running on two or more sessions.

Solution: Solution is simple we need to manage or code what ever the word.. try to have a single session always active..
for this we need to change a little coding as shown here.

private static ISession _mySession;

public static ISession mySession
        {
            get {
               
                if (!CurrentSessionContext.HasBind(SessionFactory))
                    CurrentSessionContext.Bind(SessionFactory.OpenSession());
                
                _mySession = SessionFactory.GetCurrentSession();
                return _mySession;
            }
        }

Here in the above couple of lines of code says to the NHibernate that if any session is aready bind to the Current Context then use the same session and if not create one session and bind the same to the Current Context.

Hope this Helps you….

Happy Coding 🙂

 

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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

Blog at WordPress.com.

%d bloggers like this: