I ran into this issue today when trying to persist one of my objects. The cause of the problem was interesting. I was trying to save an object when a property/columns in the table had a unique constraint. As a result, the object that I was trying to persist would not persist simply because the object's property it failed to meet the unique constraint.

As a result, a call to Save() on the object failed and the ID on the object I was trying to save was not set, but NHibernate still processed the object and associated it with its persistence mechanism leaving it in a "semi-persistent" state with the NHibernate persistence manager (ie: NHibernate now knows about the object you tried to save and it SHOULD have fully evicted the object from its persistence manager because the save failed, but it didn't).

When an HTTP request finishes on my ASP.NET application, I flush and close all NHibernate session objects at the time the request is done. And as a result, when the HTTP request finished, NHibernate attempted to flush the jacked up "semi-persistent" object (an object who's ID was null) and ultimately generating the error above.

So, the solution that I implemented was to wrap the Save() in a try{} catch{} statement, and if the save failed, immediately close and shutdown the session, handle the error/exception. Then, check if Session.IsOpen when the HTTP request finishes.

0 comments