Muz*_*ana 12 c# asp.net transactions transactionscope
我正在使用'TransactionScope',我需要在C#代码中做一些DML,我已经成功了.
我需要找出交易的状态是什么,即它是否成功完成?
因为在事务状态的基础上,如果事务完成,那么我需要执行重定向到另一个页面,否则如果事务未成功完成,那么我需要在页面上显示错误.
我想在以下后面重定向: -
scope.Complete();
scope.Dispose();
在这方面请帮助我.
Cᴏʀ*_*ᴏʀʏ 10
如果你访问MSDN页面的TransactionScope,你会发现这充分证明例如:
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);
}
Run Code Online (Sandbox Code Playgroud)
包含最多值的注释是这一个:
Complete方法提交事务.如果抛出异常,则不会调用Complete并回滚事务.
因此,如果没有抛出异常,您可以继续.放下你的重定向scope.Complete().如果抛出异常,则事务失败并自动回滚.您可以在调用之后Complete()和重定向之前仔细检查交易状态(正如其他人发布的那样),通过Transaction.Current.TransactionInformation.Status:
if (Transaction.Current.TransactionInformation.Status == TransactionStatus.Committed)
{
// do redirect
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21716 次 |
| 最近记录: |