我有一个看起来很简单的问题,但是在互联网上搜索了很久都找不到解决方案。
问题/要求: 在我的C#方法中,
- 我想开始一个事务
- 调用一些由其他人编写的包含复杂逻辑的业务逻辑,最终更新数据库。
- 检查数据库中更新后的数据。
- 无条件/强制回滚第2步中所做的更改。(即使在业务逻辑内部提交了更改)
我尝试使用 System.Transactions.TransactionScope
,但它不能按需强制回滚更改。(在调用 .Dispose
后更改不会被回滚)
我有一个看起来很简单的问题,但是在互联网上搜索了很久都找不到解决方案。
问题/要求: 在我的C#方法中,
我尝试使用 System.Transactions.TransactionScope
,但它不能按需强制回滚更改。(在调用 .Dispose
后更改不会被回滚)
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Start a local transaction.
SqlTransaction sqlTran = connection.BeginTransaction();
// Enlist a command in the current transaction.
SqlCommand command = connection.CreateCommand();
command.Transaction = sqlTran;
try
{
// Here is your "business logic"
command.CommandText = "INSERT INTO tbBusinessLogic VALUES(1)";
command.ExecuteNonQuery();
// Check result
command.CommandText = "Select 1 from tbBusinessLogic";
var result = (Int32)command.ExecuteScalar();
CheckResult(result);
// Rollback the transaction.
sqlTran.Rollback();
}
catch (Exception ex)
{
Logger.LogError(ex);
sqlTran.Rollback();
}
}
Dispose
吗? - Backs