由于here所述的原因,我需要多次调用SaveChanges。我希望这两个调用都包含在一个事务中(这样如果第二个调用失败,第一个调用将回滚)。例如:
AccountsContext context = new AccountsContext(connectionString);
CountryNotes notes = new CountryNotes();
notes.Notes = "First save";
context.SaveChanges();
notes.Notes = "Second save";
context.SaveChanges();
如何在单个交易中将上述两个调用放入SaveChanges?
谢谢,
保罗。
答案 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();
}