how to share a transaction in two dbContext with EF6?

两盒软妹~` 提交于 2020-01-01 14:35:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!