0

I have searched a lot on the Internet without finding similar case. I have one TransactionScope with several DbContext.

I want to commit changes to the database only in case all context have saved changes successfully.

But the problem I'm facing is that I had to call generalContext.SaveChanges in the middle of the code as the changes took place on data was retrieved by generalContext sometime earlier, but I noticed the changes are committed right away after calling generalContext.SaveChanges().

What problem did I do?

I have tried TransactionScopeOption.Required and TransactionScopeOption.RequiresNew, without being able to solve the problem

var transactionOptions = new TransactionOptions();
transactionOptions.Timeout = TimeSpan.FromMinutes(30);
using (var scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
using (var generalContext = new CoreEntities())
{
    try
    {

        using (var subContext = new CoreEntities())
        {
            // the problem is here, that the changes are committed!!!
            generalContext.SaveChanges();


            subContext.SaveChanges();
        }
        scope.Complete();
    }
    catch
    {
        scope.Dispose();
    }
}
Abdulkarim Kanaan
  • 1,703
  • 4
  • 20
  • 32
  • _[With the Entity Framework most of the time SaveChanges() is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction](http://stackoverflow.com/a/815660/585968)_. It's slightly different to your case; refers to an older version of EF; but it explains somethings. See also http://stackoverflow.com/a/23308945/585968 –  Jan 22 '17 at 12:35
  • Also, [Entity Framework Working with Transactions (EF6 Onwards)](https://msdn.microsoft.com/en-us/library/dn456843(v=vs.113).aspx) –  Jan 22 '17 at 12:38
  • Thanks @MickyD, but so far, still not working, if anyone can point out the problem here. Does the way of code-writing have any shortcomings which could've caused the issue at the first place? – Abdulkarim Kanaan Jan 27 '17 at 00:50

0 Answers0