2011-05-13 30 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