Share via


NHibernate: Illegal Atempt to Associate a Collection with two open sessions

Recently I got this issue when I was 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 actually happening inside the Nhibernate 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 does not 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.

01.private static  ISession _mySession;
02. 
03.public static  ISession mySession 
04.        { 
05.            get {
06.                
07.                if (!CurrentSessionContext.HasBind(SessionFactory))
08.                    CurrentSessionContext.Bind(SessionFactory.OpenSession());
09.                 
10.                _mySession = SessionFactory.GetCurrentSession();
11.                return _mySession;
12.            } 
13.        }

Here in the above couple of lines of code says to the NHibernate that if any session is already 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 http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1129645325g