问题
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.
回答1:
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);
回答2:
To add to SajidQ's answer with the better syntax
miDbContext2.Database.UseTransaction(dbContextTransaction.UnderlyingTransaction);
来源:https://stackoverflow.com/questions/20382070/how-to-share-a-transaction-in-two-dbcontext-with-ef6