1

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?

Sebastian S.
  • 1,173
  • 3
  • 13
  • 22
  • 1
    Does the [documentation](https://learn.microsoft.com/en-us/ef/core/saving/transactions) not help? – stuartd Sep 02 '17 at 14:16
  • Are you aware of the necessity of running the distributed transaction coordinator (MSDTC) when you want to commit transactions spanning multiple databases? You may want to make it easier by making EF think it only deals with one database, f.e. by using aliases. – Gert Arnold Sep 02 '17 at 17:39
  • @stuartd I am afraid it does not. I followed the documentation but it seems as they are only using contexts for the same database, so there are no ambient transactions. – Sebastian S. Sep 04 '17 at 08:11
  • @GertArnold How would you use aliases? Btw: Thanks for the hint with MSDTC, it was actually not running, but starting it did not solve the problem. – Sebastian S. Sep 04 '17 at 08:13
  • @SebastianS. Did you find out how to use aliases? Even I want to use multiple DbContext pointing to same DB inside Transaction. – Vinay Feb 27 '19 at 12:14
  • @Vinay unfortunately not – Sebastian S. Mar 05 '19 at 12:02

0 Answers0