Transaction with multiple DbContext and each with its own Entity Framework connection

I know this sounds like duplication, as there are many questions regarding transactions in multiple contexts, but none of them apply to these scenarios.

Customization

  • SQL Server 2016 (latest preview) on machine development or SQL Azure v12 on production
  • Entity Framework 6.1.3
  • .Net 4.5 in a normal application
  • The app can run on an Azure Cloud Service or VM, doesn't really matter.

What do we have in the code

  • One TransactionScope
  • Two DbContexts created outside the TransactionScope (it is created thanks to our dependency injection mechanics tied to ASP.Net MVC, so I left it for the sake of simplicity of the sample)
  • Each context creates and maintains its own connection that points to different databases on different servers (it could also point to the same server if run on a development machine, but still different databases).
  • We use regular SQL authentication - userId and password (just in case someone points out the message about problems with Integrated Security and MSDTC, we don't use it locally as it is not supported on Azure SQL)

Our sample code

When we do something like:

var contextA = new ContextA();
var contextB = new ContextB();
using(var scope = new TransactionScope())
{
     var objA = new EntityA();
     objA.Name = "object a";
     contextA.EntitiesA.Add(objA);
     contextA.SaveChanges();

     var objB = new EntityB();
     objB.Name = "object B";
     contextB.EntitiesB.Add(objB);
     contextB.SaveChanges();
     scope.Complete();
}

      

What do we get

A System.Data.Entity.Core.EntityException

is challenged contextA.SaveChanges()

with the following messages:

Root exclusion . The primary provider failed to execute the EnlistTransaction command.

Inner exception . The connection is currently completed by a transaction. Complete the current transaction and try again.

So, does anyone know what exactly is going on with this sample?

We are trying to use a single transaction using multiple contexts and each context with its own database connection. Obviously, since the data of each context is on different database servers (in production), we cannot use a DbContext ctor that receives a DbConnection and shares it with both contexts, so sharing the DbConnection is not an option.

Thanks a lot, I really appreciate any help.

+3


source to share


2 answers


Distributed transactions with TransactionScope are now supported by Azure SQL Database. See TransactionScope () in Sql Azure .



+1


source


AFAIK, distributed transactions are not supported in SQL Azure. Source



+1


source







All Articles