EF 4.1 Code First - wrap multiple calls to SaveChanges in a transaction
For reasons described here I need to make multiple calls to SaveChanges. I would like both of these calls to be wrapped up in a transaction (so that if the second call fails, 开发者_如何学运维the first call will roll back). For example:
AccountsContext context = new AccountsContext(connectionString);
CountryNotes notes = new CountryNotes();
notes.Notes = "First save";
context.SaveChanges();
notes.Notes = "Second save";
context.SaveChanges();
How do I put the above two calls to SaveChanges in a single transaction?
Thanks,
Paul.
Use 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();
}
精彩评论