NHibernate exception: Unexpected row count: 0; expected: 1

While working on a project that uses NHibernate I was receiving the exception Unexpected row count: 0; expected: 1 after some investigation I found out that the problem was caused by me not setting an attribute in the mapping file.

I had a table in a sql server 2000 database that had an Id column this was set to an identity column, in my mapping file I had the following:


    

I kept getting the exception the moment I made a call to SaveOrUpdate using a new object that was associated with the table and then flushing the session, calls to already existing objects in the database were fine (Id property set) It turned out that because I was using -1 as the default for an object that was not saved NHibernate did not know that this was a new object to be inserted.

The fix was to change the mapping file to this:


    

Advertisements

7 thoughts on “NHibernate exception: Unexpected row count: 0; expected: 1

  1. The better solution to this is to save the detached child object, before saving the parent, so that the child obtains a valid Id.

  2. Thanks a lot 🙂 Had the exact same problem today (even -1). First google search -> top-result -> here. First time I’ve fixed a bug this fast 🙂

  3. This also occurs if you are trying to insert a new record into a table that has a composite key. If you call SaveOrUpdate instead of Save this would also generate the same message.

Comments are closed.