我有一個nHibernate競爭條件,這是在我的數據庫上創建重複條目。不幸的是,我不能在數據庫上創建一個UNIQUE
索引,因此我只想用nHibernate方法來解決這個錯誤。這是一個Web應用程序,可能運行在網上農場(因此我猜系統鎖也不應該解決問題)。簡化情況如下:競爭條件使nHibernate創建重複條目
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的新手,所以也許我缺少一些基礎知識。我會很感激任何反饋。 :)
myEntity.Save();應該在交易中。 –
你的競賽狀況的性質不是很清楚。 –
您正在查找的數據庫概念是一項交易。您需要創建一個鎖定事務,以便從GetBy開始更新並在保存結束。然而,我可以告訴你如何在Hibernate中做到這一點。 –