2

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.

Community
  • 1
  • 1
P2l
  • 915
  • 2
  • 11
  • 25

1 Answers1

2

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();
}
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • So to do this I would need to enable DTC for network access in the security configuration for MSDTC - at least that's what the exception is telling me when I try this code. I would like to avoid this if possible as it will require more configuration changes for user sites. – P2l May 13 '11 at 14:05