我在我的webapp中看到一些奇怪的競爭條件,我懷疑這可能是由於Entity Framework以意外的方式處理讀鎖。當我的應用程序向任何頁面發出請求時,我會自動加載帳戶模型,然後將其存儲在我的DbContext中,以保存請求的整個生命週期。某些網頁需要鎖定帳戶DB行,以便在沒有競爭條件的情況下安全地執行其他操作。下面是我現在怎麼做這個...實體框架事務鎖定
//... code that begins the request and loads the account into context.
// Some pages may run code that looks something like this.
using(var tran = existingCtx.Database.BeginTransaction(IsolationLevel.RepeatableRead))
{
// Lock customer.
var act = ctx.Accounts.Find(purchaseFor.ID);
if (act == null)
throw new RecordNotFoundException("Unable to find specified customer.");
DoStuffRelyingOnLock();
Commit();
}
會將呼叫查找查找(purchaseFor.ID)鎖定在數據庫中的帳戶行,即使它已經加載到背景?
是否沒有隱式回滾?如果沒有,那麼實現'IDisposable'的事務有什麼意義呢? – Blorgbeard
請參閱mdsn文檔[鏈接](https://msdn.microsoft.com/en-us/data/dn456843.aspx)以查看EF上下文中的using語句和正確的事務處理。 – btberry
是的,你所建議的是好的做法。但是,說OP的代碼會讓事務處於開放狀態是完全錯誤的。事務實例將被放置在'using'塊的末尾。這包括如果當時交易仍然開放,則調用回滾。 – sstan