Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 395
Álvaro García Avatar asked Dec 04 '13 17:12

Álvaro García


People also ask

What are the transactions in Entity Framework 6?

Here you will learn about the transactions in EF 6.x & EF Core. In Entity Framework, the SaveChanges () method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges () calls, create separate transactions, perform CRUD operations and then commit each transaction.

What is multiple dbcontext in Entity Framework?

Entity Framework - Multiple DbContext. In this chapter, we will be learning how to migrate changes into the database when there are multiple DbContext classes in the application. Multiple DbContext was first introduced in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases.

What is the use of dbcontext usetransaction?

The DbContext.Database.UseTransaction () method allows us to use an existing transaction created out of the scope of the context object. If we use the UseTransaction () method, then the context will not create an internal transaction object and will use the supplied transaction.

Should I use TransactionScope in EF6?

Prior to EF6, using TransactionScopewas the only practical way to control the database transaction scope and isolation level. In practice, and unless you actually need a distributed transaction, you should avoid using TransactionScope.


2 Answers

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);
like image 180
SajidQ Avatar answered Oct 01 '22 18:10

SajidQ


To add to SajidQ's answer with the better syntax

  miDbContext2.Database.UseTransaction(dbContextTransaction.UnderlyingTransaction);
like image 20
GregJF Avatar answered Oct 01 '22 19:10

GregJF