2011-05-13 33 views
2

由於原因here我需要對SaveChanges進行多次調用。我希望這兩個調用都包含在一個事務中(這樣如果第二個調用失敗,第一個調用將回滾)。例如:EF 4.1代碼優先 - 在交易中將多次調用包裝到SaveChanges

AccountsContext context = new AccountsContext(connectionString); 

CountryNotes notes = new CountryNotes(); 
notes.Notes = "First save"; 
context.SaveChanges(); 

notes.Notes = "Second save"; 
context.SaveChanges(); 

我如何把上面兩個調用的SaveChanges在一個單一的交易?

謝謝,

保羅。

回答

2

使用TransactionScope

using (var scope = new TransactionScope(TransactionScopeOption.Required, 
    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted })) 
{ 
    AccountsContext context = new AccountsContext(connectionString); 

    CountryNotes notes = new CountryNotes(); 
    notes.Notes = "First save"; 
    context.SaveChanges(); 

    notes.Notes = "Second save"; 
    context.SaveChanges(); 

    scope.Complete(); 
} 
+0

因此,要做到這一點,我需要讓DTC在用於MSDTC的安全配置網絡接入 - 至少這是什麼異常告訴我,當我嘗試此代碼。如果可能,我想避免這種情況,因爲它需要對用戶站點進行更多配置更改。 – P2l 2011-05-13 14:05:16