Álvaro García
Álvaro García

Reputation: 19396

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.

Upvotes: 5

Views: 3458

Answers (2)

SajidQ
SajidQ

Reputation: 158

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);

Upvotes: 6

GregJF
GregJF

Reputation: 466

To add to SajidQ's answer with the better syntax

  miDbContext2.Database.UseTransaction(dbContextTransaction.UnderlyingTransaction);

Upvotes: 3

Related Questions