Search code examples
asp.net-coreef-core-3.1

Do we need to explicitly call Rollback after a failed database transaction


Most of the code implementing transactions I come across, call Rollback explicitly. Do we need to call Rollback? Doesn't Dispose call Rollback automatically? What's the purpose of explictly calling Rollback?

Thanks all.

public void DatabaseUpdate ()
{
  using var MyTransaction = MyContext.Database.BeginTransaction () ;

  if (MethodIsSuccessful ())
  {
    MyTransaction.Commit () ;
  }
  else
  {
    // MyTransaction.Rollback () ;  // Not necessary, will be called by Dispose, right ?
  }
}

Solution

  • Dispose() does not call Rollback(), it merely cleans up the transaction object and ensures the Entity Framework is no longer using that transaction.

    So that brings us to the database. The Sql Server documentation states that

    Depending on the current transaction isolation level settings, many resources acquired to support the Transact-SQL statements issued by the connection are locked by the transaction until it is completed with either a COMMIT TRANSACTION or ROLLBACK TRANSACTION statement. Transactions left outstanding for long periods of time can prevent other users from accessing these locked resources, and also can prevent log truncation.

    So yes, you do need to call Rollback() explicitly, if that is your intention.