NHibernate を使用してデータベースに非同期で保存するときに、競合状態の問題が発生しています。最初にデータベースへの挿入が非同期で行われ、一意の ID が自動生成されます。この挿入がメイン スレッドに戻る前に、データベースで生成された一意の ID を持つ現在永続化されたオブジェクトを使用して、オブジェクトが何らかの方法で更新されます。更新するオブジェクトにはまだ ID 値がないため、session.Update を呼び出すと更新が失敗します。SaveOrUpdate を呼び出すと、エンティティの id フィールドが unsaved-value プロパティと等しいため、明らかに Update ではなく挿入になります。このコードで状況がより明確になることを願っています。
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
1 つの解決策は、保存する前にコードで一意の ID を生成することです。この場合、データベースではなく、アプリケーションが一意の ID の増分を管理します。これを処理する他の方法はありますか?