回滚C#中的临时DB更改

时间:2015-11-24 07:44:58

标签: c# sql-server transactions sql-server-2012

我有这个问题看似简单,但一直在网上搜索,无法找到解决方案。

问题/要求: 在我的c#方法中,

  1. 我想开始交易
  2. 调用一些最终用复杂逻辑更新DB的业务逻辑。(由其他人编写)
  3. 检查数据库中的更新数据。
  4. 无条件/强制地回滚在step2中完成的更改。(即使在业务逻辑中提交了更改)
  5. 我尝试使用System.Transactions.TransactionScope,但无法按需强制回滚更改。 (调用.Dispose时)不会回滚更改

2 个答案:

答案 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();
    }
}