【问题标题】:EF 4.1 Code First - wrap multiple calls to SaveChanges in a transactionEF 4.1 Code First - 在事务中包装对 SaveChanges 的多个调用
【发布时间】:2011-05-13 21:42:25
【问题描述】:

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

AccountsContext context = new AccountsContext(connectionString);

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

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

如何将上述两个 SaveChanges 调用放在一个事务中?

谢谢,

保罗。

【问题讨论】:

    标签: transactions ef-code-first entity-framework-4.1


    【解决方案1】:

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

    【讨论】:

    • 因此,我需要在 MSDTC 的安全配置中启用 DTC 以进行网络访问——至少当我尝试此代码时,异常告诉我的是这样。如果可能的话,我想避免这种情况,因为它需要对用户站点进行更多的配置更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多