如何使用EF6在两个dbContext中共享事务? [英] how to share a transaction in two dbContext with EF6?

查看:479
本文介绍了如何使用EF6在两个dbContext中共享事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF6,我知道有两种使用事务的方法BeginTransaction和UseTransaction。

I am using EF6 and I know that has two methods to use a transaction, BeginTransaction and UseTransaction.

我过去只使用一个dbContext,但就我而言,我需要使用辅助dbContext,并且我需要第二个dbContext使用与主dbContext相同的事务。我尝试使用此代码:

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

但是UseTransaction出现错误,因为miTrasaccion是

But I get an error in the UseTransaction because miTrasaccion is not of the correct type.

我想知道如何在两个dbContext之间共享同一事务。

I would like to know how I can shared the same transaction between two dbContexts.

谢谢。

推荐答案

您需要先将miDbContext的连接传递给miDbContext2。

You need to pass the connection of miDbContext to miDbContext2 first.

尝试以下代码。

Entities miDbContext2 = new Entities(miDbContext.Database.Connection, false);
miDbContext2.DataBase.UseTransaction(miTransaccion);

这篇关于如何使用EF6在两个dbContext中共享事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆