Mark13426
Mark13426

Reputation: 2639

Rollback transactions made by two different DBContext saves when an exception occurs

I need to save to two different databases after some user action. Currently, I have the following:

using (EFEntities1 dc = new EFEntities1())
{
     dc.USERS.Add(user);
     dc.SaveChanges();
}

using (EFEntities2 dc = new EFEntities2())
{
     dc.USERS.Add(user);
     dc.SaveChanges();
}

These are two separate code blocks within the same method, so I believe if the second one fails, the first one won't rollback. How do I make sure both transactions rollback if something fails?

Upvotes: 0

Views: 406

Answers (1)

Mark Oreta
Mark Oreta

Reputation: 10416

You can wrap them in a TransactionScope. Note that this will probably call the DTC.

using (TransactionScope scope = new TransactionScope())  
{
  using (EFEntities1 dc = new EFEntities1())
  {
     dc.USERS.Add(user);
     dc.SaveChanges();
  }

  using (EFEntities2 dc = new EFEntities2())
  {
     dc.USERS.Add(user);
     dc.SaveChanges();
  }

  scope.complete();
}

Upvotes: 2

Related Questions