.NET Zone is brought to you in partnership with:

Working with a Bangalore based software company. I spend most of my time working in Microsoft Technologies. Author of Neo4jD and iTraveller. Neo4jD is a Neo4j graph database client for .NET and iTraveller is an application to upload photos to both flickr and Facebook. Sony is a DZone MVB and is not an employee of DZone and has posted 25 posts at DZone. You can read more from them at their website. View Full User Profile

StaleStateException for Entity with Assigned Id and Version in NHibernate

05.04.2013
| 2861 views |
  • submit to reddit

I was trying to persist an entity using NHibernate that uses Assigned Id’s and Version concurrency mechanism. Every time I try to persist a new instance, I am getting a StaleStateException. As per my knowledge the concurrency check will happen when we try to do an update, in my scenario it’s throwing while doing an insert. Also in the nhibernate log, I could see nhiberate is firing update command instead of insert. 

After doing some googling I come across a stackoverflow post, that NHibernate will fire update or insert based on three parameters.

  1. Id
  2. Version
  3. Timestamp

In my case Id is assigned and it will exist even if it’s a new data and I can’t help it. I am not using Timestamp. So the issue narrowed down to Version. Entity do have a version and unfortunately it’s updated using Automapper, while converting DTO to Entity. I use unix timestamp as version and we added a custom mapping in automapper to fill current date in unix timestamp format if version field is coming as empty from the client and is useful in update scenario. So for NHibernate this is not a new data because it has Id and version, so it will try to do an update instead of insert and that causes all the issues for me.

To solve this issue, either we can use Save() instead of SaveOrUpdate() or set version to zero for new data.

Published at DZone with permission of Sony Arouje, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)