使用相同连接的TransactionScope和方法调用 [英] TransactionScope and method call that uses the same connection

查看:141
本文介绍了使用相同连接的TransactionScope和方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 TransactionScope 可以使一个包含多个事务性SQL语句的方法。现在,我需要调用也使用相同连接的第二种方法,并且在 connection.Open()处收到以下异常:

I'm using TransactionScope to make a method that contains multiple sql statements transactional. Now i need to call a second method that also uses the same connection and i receive following exception at connection.Open():


已禁用
的分布式事务管理器(MSDTC)的网络访问权限。请使用组件服务管理
工具在MSDTC的安全
配置中为网络访问启用DTC。

Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

因此,这是伪代码:

public static void Method1()
{
    using (TransactionScope scope = new TransactionScope())
    {
        bool success = true; // will be set to false in an omitted catch
        using (var connection = new SqlConnection(ConnectionString1))
        {
           // ...
           if(somethingHappened)
               Method2();
        }
        if(success)
            scope.Complete();
    }
}

public static void Method2()
{
    using (var connection = new SqlConnection(ConnectionString1))
    {
        connection.Open(); // BOOOM!
        // ...
    }
}

如何避免重复此代码而不重复 Method1 Method2 中的代码?

How to avoid this exception without repeating the code from Method2 in Method1?

推荐答案

如果在同一 TransactionScope 下打开了多个连接,它将自动升级为DTC。

If more then one connection are open under same TransactionScope it will be automatically escalated to the DTC.

您需要先关闭第一个连接,然后再调用 Method2

You need to close first connection before calling Method2.

public static void Method1()
{
    using (TransactionScope scope = new TransactionScope())
    {
        bool success = true; // will be set to false in an omitted catch

        bool isSomethingHappened
        using (var connection = new SqlConnection(ConnectionString1))
        {
           isSomethingHappened = // Execute query 1
        }

       if(somethingHappened)
           Method2();

        if(success)
            scope.Complete();
    }
}

这篇关于使用相同连接的TransactionScope和方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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