c# – TransactionScope不回滚事务

这是我的交易范围源代码的当前体系结构.第三个插入引用.NET异常(不是sql异常),而不是回滚两个先前的insert语句.我做错了什么?

编辑:我从insert2和insert3中删除了try / catch.我还从insert1 try / catch中删除了异常处理实用程序,并放置“throw ex”.它仍然不会回滚事务.

编辑2:我在Insert3方法添加了try / catch,只是在catch语句中放了一个“throw”.它仍然不会回滚事务.

更新:根据我收到的反馈,“sqlHelper”类使用sqlConnection对象建立与数据库的连接,然后创建一个sqlCommand对象,将CommandType属性设置为“StoredProcedure”并调用sqlCommand的ExecuteNonQuery方法.

我也没有将Transaction Binding = Explicit Unbind添加到当前的连接字符串.我会补充说,在我的下一个测试.

public void InsertStuff()
{
    try
    {
        using(TransactionScope ts = new TransactionScope())
        {
            //perform insert 1
            using(sqlHelper sh = new sqlHelper())
            {
                sqlParameter[] sp = { /* create parameters for first insert */ };

                sh.Insert("MyInsert1",sp);
            }

            //perform insert 2
            this.Insert2();

            //perform insert 3 - breaks here!!!!!
            this.Insert3();

            ts.Complete();            
        }
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

public void Insert2()
{
    //perform insert 2
    using(sqlHelper sh = new sqlHelper())
    {
        sqlParameter[] sp = { /* create parameters for second insert */ };

        sh.Insert("MyInsert2",sp);
    }
}

public void Insert3()
{
    //perform insert 3
    using(sqlHelper sh = new sqlHelper())
    {
        sqlParameter[] sp = { /*create parameters for third insert */ };

        sh.Insert("MyInsert3",sp);
    }
}

解决方法

我也遇到类似的问题.我的问题出现是因为我在sqlCommands中使用的sqlConnection在TransactionScope创建之前已经打开,因此它不会作为事务登录在TransactionScope中.

sqlHelper类是否可以重新使用在输入TransactionScope块之前打开的sqlConnection实例?

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么