EF 4.1 Code First - 在事务中包含对SaveChanges的多个调用

时间:2011-05-13 13:37:59

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

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

AccountsContext context = new AccountsContext(connectionString);

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

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

如何在单个交易中将上述两个调用放入SaveChanges?

谢谢,

保罗。

1 个答案:

答案 0 :(得分: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();
}