我有这个问题看似简单,但一直在网上搜索,无法找到解决方案。
问题/要求: 在我的c#方法中,
我尝试使用System.Transactions.TransactionScope
,但无法按需强制回滚更改。 (调用.Dispose
时)不会回滚更改
答案 0 :(得分:1)
如果提交了一个事务,它就会被提交。事后没有回滚。这就是承诺的重点。您最终必须更改外国代码。
答案 1 :(得分:0)
如果“某些业务逻辑”不是您自己的数据库调用(即连接库中的某些方法),那么您无法回滚更改(如果该逻辑的开发人员不提供此类可能性)。
但是如果那个逻辑只是一些数据库调用,那么你可以在没有提交的情况下回滚你的事务。
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();
}
}