Search code examples
entity-frameworktransactions

how to share a transaction in two dbContext with EF6?


I am using EF6 and I know that has two methods to use a transaction, BeginTransaction and UseTransaction.

I use to use only one dbContext, but in my case, I need to use an auxiliar dbContext and I need that this second dbContext use the same transaction that the main one. I try to use this code:

using(Entities miDbContext = new Entities())
{
    using (DbContextTransaction miTransaccion = miDbContext.Database.BeginTransaction())
    {
        Entities miDbContext2 = new Entities();
        miDbContext2.DataBase.UseTransaction(miTransaccion);
    }
}

But I get an error in the UseTransaction because miTrasaccion is not of the correct type.

I would like to know how I can shared the same transaction between two dbContexts.

Thanks.


Solution

  • You need to pass the connection of miDbContext to miDbContext2 first.

    Try the below code. It should work.

    Entities miDbContext2 = new Entities(miDbContext.Database.Connection, false);
    miDbContext2.DataBase.UseTransaction(miTransaccion.UnderlyingTransaction);