Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SaveChanges() for multiple dbcontext with TransactionScope in Entity Framework 4.1

I am using SaveChanges() method as given below:

objAdbContext of Database A

objBdbContext of Database B

Updating table of DB A as given below

public string SaveA()
{

//Some stuff

  objAdbContext.SaveChanges();

  string result=UpdateDatabaseB(some parameters)

  //Some stuff

}


public string UpdateDatabaseB(some parameters)

{

  //Some stuff

   objBdbContext.SaveChanges();

  return "Success";

}

This case Database B is not getting updated. Is it correct way of updating multiple databases?

Both are independent Databases and How to implement TransactionScope in this case?

like image 453
mastan Avatar asked Mar 27 '26 05:03

mastan


1 Answers

Try this:

using (TransactionScope scope = new TransactionScope())
{
    // Save changes but maintain context1 current state.
    context1.SaveChanges(SaveOptions.DetectChangesBeforeSave);

    // Save changes but maintain context2 current state.
    context2.SaveChanges(SaveOptions.DetectChangesBeforeSave);

    // Commit succeeded since we got here, then completes the transaction.
    scope.Complete();

    // Now it is safe to update context state.
    context1.AcceptAllChanges();
    context2.AcceptAllChanges();
}

This sample was taken from this blog post:

Managing Transactions with Entity Framework 4

like image 186
Rui Jarimba Avatar answered Mar 29 '26 19:03

Rui Jarimba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!