I am having a problem with a race condition when saving to the database asynchronously using NHibernate. First an insert to the database is done asynchronously where the unique id is auto-generated. Before this insert returns back to the main thread with now persisted object that has the unique database generated id, the object in updated in some way. The update will fail if I call session.Update because the object to be updated does not have a an id value yet. If I call SaveOrUpdate it will obviously result in an insert instead of an Update because the id field of my entity is equal to the unsaved-value property. Hopefully this code makes the situation more clear:
Entity entity = new Entity()
//update some fields
entity.PropertyTwo = "new value";
//dataObject as the database auto-generated Id
//insert new row asynchronously in different thread
Entity entity.Id = dao.save(entity.Clone()).Id
//before the the entity is returned from the database, the entity might be updated
entity.Property = 'new value';
//entity might be sent without an Id since the first asynch call has not returned yet.
//update asynchronously in another thread
Object dataObject = dao.Update(entity); //fails because Id is not set yet
One solution is to generate the unique id in the code prior to saving. In this case the application manages the incrementing of the unique id as opposed to the database. Any other ways of handling this?