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.
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.
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.
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.
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.
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);
To add to SajidQ's answer with the better syntax
miDbContext2.Database.UseTransaction(dbContextTransaction.UnderlyingTransaction);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With