NHibernate: Unexpected row count: 0; expected: 1

Posted by Zafar Ullah - zafarjcp@gmail.com | 6:32 AM | , , , , | 0 comments »

here are some of my experiences when "Unexpected row count: 0; expected: 1" comes and also how can we solve them.

1. If primarykey generator has some issue e.g you in class its identity and in db its not an identity column. For those columns where your db column is not identity and its part of a requirment then "hilo" works :) for details on generator clickhere

2. Nhibernate seems to have problems when you create multiple transient entities that reference each other, and then try to save just the root entity. To avoid these problems, call
session.Save() on each transient entity after you create it, before you attach it to others else
use session.Update().

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.