NHibernate - null id in entry (don’t flush the Session after an exception occurs)
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.
Hope that helps,
Brian Chavez
Comments
Hazi
thank you for this post…it helped me out.
Guillermo
Thank you very much for blog entry. It explained a very frustrating error i was having. I disagree with your explanation but your explanation is excellent. Thanks!
Mikkell
This error can also occour when using reserved words as column names in the database.
Zoran
Hi Brian,
nice article, but do you maybe know why NHibernate have problem of writing “null” types? I assigned to DateTime? variable “null” and I traced back up to persistancemanager.cs the call:
etcSession.Save(item);//time still == null
etcSession.Transaction.Commit();// writing to mySql and somehow converting Date to current date. How to make NHibernate write null for the date ?
Thanks&BR,
Zoran
Aline
actually, this error can occur with something so simple as an improper mapping
humtum
Where is the answer. Fuck it.
Leave a comment
Your email address will not be published. Required fields are marked *