Ambient transaction across multiple contexts pointing to other databases

1.1k Views Asked by At

Short description of the setup:

EF Core is used with fluent mapping. There are three databases and for each database one context. The problem is to begin a transaction scope across two or all the three contexts. The OnConfiguration method is overridden in each context like this example:

public class MyContext : DbContext
{
    private string _connectionString;

    public MyContext(string connectionString)
    {
        _connectionString = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        /* Replace a placeholder with the database name */
        optionsBuilder.UseSqlServer(string.Format(_connectionString, "database1");
    }    
}

What I already tried to begin a transaction:

Begin a transaction on a context and pass it to another context

using (var transaction = context1.Database.BeginTransaction()) 
{
    context2.Database.UseTransaction(transaction.GetDbTransaction());
    /*do something on context1*/
    /*do something on context2*/

    transaction.Commit();
}

Begin a transaction scope

using (var scope = new TransactionScope()) 
{
    /*do something on context1*/
    /*do something on context2*/
    /*do something on context3*/

    scope.Complete();
}

EF throws on each way an ambient transaction exception.

I found somewhere in the internet another solution (lost the link, sorry guys). They passed not the connection string to the context, instead of this they passed the connection itself to the context. But I do not understand how it should be possible to connect to different databases in the contexts then.

Has anyone a solution to solve this problem?

0

There are 0 best solutions below