Illegal Attempt to Associate a Collection with Two Open Sessions

Illegal Attempt to Associate a Collection with Two Open Sessions

Hi All recently I got this issue when I am 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 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 doesn't 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 :)

Leave a Comment
  • Please add 1 and 1 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Richard Mueller edited Revision 1. Comment: Fix title, fix typo

  • Maheshkumar S Tiwari edited Original. Comment: Added tags ,title casing and minor edit

Page 1 of 1 (2 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • Maheshkumar S Tiwari edited Original. Comment: Added tags ,title casing and minor edit

  • Richard Mueller edited Revision 1. Comment: Fix title, fix typo

Page 1 of 1 (2 items)