6

I am using EF 6.1 with .NET 4.6.1.

If I create a transaction scope with TransactionScopeAsync inside a using block on the dbContext and then update data in the database directly with dbContext.Database.ExecuteSqlCommand and then call the same entity from the database with a LINQ query inside the same transaction scope, it will not show the updated data.

Example:

using (MyDbContext dbContext = new MyDbContext())
{
    using (TransactionScope txScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
    {
        dbContext.Database.ExecuteSqlCommand("UPDATE TestTable SET TestText = 'A' WHERE ID = 1;");
        var testObject_A = (from t in dbContext.TestTable where ID == 1 select t.TestText).FirstOrDefault();
        // THIS WILL HAVE "A"

        dbContext.Database.ExecuteSqlCommand("UPDATE TestTable SET TestText = 'B' WHERE ID = 1;");
        var testObject_B = (from t in dbContext.TestTable where ID == 1 select t.TestText).FirstOrDefault();
        // THIS WILL HAVE "A" <-- It should have been a "B"

        txScope.Complete();
    }
}

If I update something on the TestTable it show correctly the first time.
Once I query the textOject I will see the changes on the TestTable.
BUT if I then run another update on textOject and then try to run a LINQ query on the same db context I will not see the changes.

What am I missing?

Also I can't use context.Database.BeginTransaction because I have parent transaction scopes created outside the current method and I need them to join the parent transaction.
BeginTransaction does not offer a way of joining transactions from outside callers / parents without passing existing connections from parent to child method OR I can't seem to find any article on how to do this in EF 6.

https://msdn.microsoft.com/en-us/library/dn456843(v=vs.113).aspx

goroth
  • 2,510
  • 5
  • 35
  • 66

0 Answers0