Tag Archives: NoneReferrence

Handling nullreference exception problems encountered in NHibernate

Recently, when using NHibernate, we encountered a very strange problem. When calling Session.SaveOrUpdate () method, an exception was thrown.

 

Look at the screenshot below. Although this exception was caught by vs in the catch line, the real problem is inside the try code block. As for how to make vs catch and prompt when problems occur, there is a detailed introduction in my other blog articles. I won’t talk about it here.

 

The code to throw an exception is as follows:

 

 

 

 

In the end, it’s the call Session.SaveOrUpdate The exception thrown when (). And I’ll go to the details of exception to see if there are any hints, but there are no valuable clues such as innerexcitation and message. Later, I kept thinking about why there was a problem, and finally found the root of the problem, which is current_ session_ context_ There’s something wrong with class.

 

The scene is like this. My project is a web project, in which NHibernate is used, and then I write the configuration in the web.config In the middle. After that, I wrote some new methods, and then set up a unittest project. Later, I need to move all the content related to NHibernate in order to test these service methods. I’ll take it web.config The content in is copied to the app.config The session context in NHibernate is still web, which is the reason for the problem.

 

 

Then I changed it to thread_ Static, the problem is solved. The reason is that the project of unittest does not have IIS. If session is still obtained from the web at this time, it will be null, so an exception is thrown.