c# – 如何查找交易状态

前端之家收集整理的这篇文章主要介绍了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
}
原文链接:https://www.f2er.com/csharp/97033.html

猜你在找的C#相关文章