Transactions EF 4.1代码优先-包装多个调用以保存事务中的更改

Transactions EF 4.1代码优先-包装多个调用以保存事务中的更改,transactions,ef-code-first,entity-framework-4.1,Transactions,Ef Code First,Entity Framework 4.1,出于上述原因,我需要多次调用SaveChanges。我希望这两个调用都打包在一个事务中(这样,如果第二个调用失败,第一个调用将回滚)。例如: AccountsContext context = new AccountsContext(connectionString); CountryNotes notes = new CountryNotes(); notes.Notes = "First save"; context.SaveChanges(); notes.Notes = "Secon

出于上述原因,我需要多次调用SaveChanges。我希望这两个调用都打包在一个事务中(这样,如果第二个调用失败,第一个调用将回滚)。例如:

AccountsContext context = new AccountsContext(connectionString);

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

notes.Notes = "Second save";
context.SaveChanges();
如何在单个事务中调用上述两个SaveChanges

谢谢


保罗。

使用
交易范围

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();
}

因此,要做到这一点,我需要在MSDTC的安全配置中为网络访问启用DTC-至少当我尝试此代码时,异常会告诉我这一点。如果可能的话,我希望避免这种情况,因为这将需要对用户站点进行更多的配置更改。