c# - Entity Framework 中的一个事务中的多个数据库

标签 c# asp.net .net entity-framework transactions

我在 Entity Framework 中为两个不同的数据库创建了两个不同的上下文。现在我正在尝试在单个事务中更新这些数据库。我的代码是这样的:

public class LPO_BLL
{
    internal Context1 _context1 = null;
    internal Context2 _Context2 = null;

    public LPO_Detail_BLL(Context1 context1, Context2 context2)
    {
        _context1 = context1;
        _context2 = context2;
    }

    public void Insert(PM_LPO lpo, LPO_Transaction lpo_transaction)
    {
        using (TransactionScope transaction = new TransactionScope())
        {
            _context1.LPO.Add(lpo);
            _context1.SaveChanges();

            _context2.LPO_Transaction.Add(lpo_transaction);
            _context2.SaveChanges();  // I am getting error here...

            transaction.Complete();
        }
    }
}

在 UI 项目中,我将其称为:

LPO lpo = new LPO();
//setting properties of lpo

LPO_Transaction lpo_trans = new LPO_Transaction();
//setting properties of lpo_trans

Context1 _context1 = new Context1();
//Opening _context1 connection and etc

Context2 _context2 = new Context2();
//Opening _context2 connection and etc

LPO_BLL lpo_bll = new LPO_BLL(_context1, _context2);

lpo_bll.Insert(lpo,lpo_trans);

目前,我收到错误: 基础提供商在 EnlistTransaction 上失败

在互联网上搜索了过去 3 个小时并尝试了不同的点击和试用方法后,我决定将其放在 SO 上。到目前为止,我发现这两个链接更接近:

http://social.msdn.microsoft.com/Forums/en-US/3ccac6f7-6513-4c87-828a-00e0b88285bc/the-underlying-provider-failed-on-enlisttransaction?forum=adodotnetentityframework

TransactionScope - The underlying provider failed on EnlistTransaction. MSDTC being aborted

最佳答案

并非所有数据库提供商都支持分布式事务。

使用事务范围将尝试将数据库事务加入到由 MSDTC 管理的分布式事务中。如果您的提供商不支持此功能,它将失败。

SQL Server 和 Oracle 提供程序支持分布式事务。但许多其他 EF 提供商并不这样做。

如果您的数据库提供商不支持此功能,您将不得不使用其他数据库提供商或放弃使用事务。

如果您使用的是 SQL Server 2005,它应该可以工作,但是:

  • MSDTC 服务必须正在运行(在控制面板的“服务”中查找)。
  • 连接字符串必须足以让 MSDTC 正常工作

看看this SO Q&A: confusion about transactions and msdtc .

注意:该服务的名称是 MSDTC。因此,您可以运行 net start msdtcnet stop msdtc。如果您在控制面板中查找它,您会找到一个描述性名称,例如“分布式事务协调器”或本地化名称,例如“Coordinador de transacciones distribuidas”。奇怪的是,本地服务的控制面板列表中无法显示名称栏。

关于c# - Entity Framework 中的一个事务中的多个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20468245/

相关文章:

c# - 从数据库中获取动态按钮花费的时间太长

c# - 使用带偏移的 Raycast 命中点移动对象

c# - 检查控制字符

c# - 是否可以将单击事件用于WPF(MVVM)中的小型操作?

c# - 使用 Azure 应用服务的 Web 应用程序和移动客户端具有相同的业务逻辑

javascript - asp.net 文本框中仅允许数字或小数数据

c# - 如何控制自动生成的字段 gridview 的列数

c# - 如何使用 C# 在 mysql 5.1 版本中插入 unicode 值?

c# - Controller 中的 NullReferenceException C#

c# - 扩展 App.config 中的元素