c# – 如何查找交易状态

我正在使用“TransactionScope”,我需要在C#代码中做一些DML,我已经成功了.

我需要知道交易的状态是什么,那是否成功完成?

因为在事务状态的基础上,如果事务完成,那么我需要执行重定向到另一个页面,否则如果事务没有成功完成,那么我需要在页面显示错误.

我想重定向以下:

scope.Complete();
scope.dispose();

请帮忙我这个问题.

解决方法

如果您为TransactionScope visit the MSDN page,您会发现这个有据可查的例子:
try
{
    // Create the TransactionScope to execute the commands,guaranteeing
    // that both commands can commit or roll back as a single unit of work.
    using (TransactionScope scope = new TransactionScope())
    {
        using (sqlConnection connection1 = new sqlConnection(connectString1))
        {
            // opening the connection automatically enlists it in the 
            // TransactionScope as a lightweight transaction.
            connection1.open();

            // Create the sqlCommand object and execute the first command.
            sqlCommand command1 = new sqlCommand(commandText1,connection1);
            returnValue = command1.ExecuteNonQuery();
            writer.WriteLine("Rows to be affected by command1: {0}",returnValue);

            // If you get here,this means that command1 succeeded. By nesting
            // the using block for connection2 inside that of connection1,you
            // conserve server and network resources as connection2 is opened
            // only when there is a chance that the transaction can commit.   
            using (sqlConnection connection2 = new sqlConnection(connectString2))
            {
                // The transaction is escalated to a full distributed
                // transaction when connection2 is opened.
                connection2.open();

                // Execute the second command in the second database.
                returnValue = 0;
                sqlCommand command2 = new sqlCommand(commandText2,connection2);
                returnValue = command2.ExecuteNonQuery();
                writer.WriteLine("Rows to be affected by command2: {0}",returnValue);
            }
        }

        // The Complete method commits the transaction. If an exception has been thrown,// Complete is not  called and the transaction is rolled back.
        scope.Complete();

    }

}
catch (TransactionAbortedException ex)
{
    writer.WriteLine("TransactionAbortedException Message: {0}",ex.Message);
}
catch (ApplicationException ex)
{
    writer.WriteLine("ApplicationException Message: {0}",ex.Message);
}

包含最多价值的评论是这个:

The Complete method commits the transaction. If an exception has been thrown,Complete is not called and the transaction is rolled back.

所以,如果没有抛出异常,你可以继续.把你的重定向放在scope.Complete()之后.如果抛出异常,则事务失败并自动回滚.调用Complete()之后,以及在您通过Transaction.Current.TransactionInformation.Status重定向之前,可以重新审核事务状态(和其他人一样):

if (Transaction.Current.Transactioninformation.Status == TransactionStatus.Committed) 
{
    // do redirect
}

相关文章

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