我在nHibernate上遇到了竞态条件,导致我的数据库中出现了重复条目。 不幸的是,我不能在数据库中创建一个唯一索引,因此我想仅使用nHibernate方法解决此错误。 这是一个可能在Web农场上运行的Web应用程序(因此我猜系统锁也无法解决问题)。 简化后的情况如下:
var current = UnitOfWorkManager.Instance.Current;
current.BeginTransaction(IsolationLevel.Serializable);
try {
var myEntity = MyFactory.MyEntityRepository.GetBy(product, company);
// race condition happens between the previous statement and Save() method.
if (myEntity == null)
{
myEntity = new MyEntity();
myEntity.Product = product;
myEntity.Company = company;
myEntity.Date = date;
myEntity.CurrentUser = currentUser;
myEntity.IsManual = true;
myEntity.Save();
}
else
{
myEntity.IsManual = false;
myEntity.Save();
}
current.CommitTransaction();
}
catch {
current.RollbackTransaction();
throw;
}
我对nHibernate还不熟悉,可能会忽略一些基础知识。非常感谢您的反馈。:)