Cypher
Cypher

Reputation: 47

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 ?
  }
}

Upvotes: 0

Views: 982

Answers (2)

blackforest-tom
blackforest-tom

Reputation: 487

No, it is not required to call .Rollback() or .RollbackAsync() if you are disposing of the transaction without committing it.

From the official docs (https://learn.microsoft.com/en-us/ef/core/saving/transactions):

Commit transaction if all commands succeed, transaction will auto-rollback when disposed if either commands fails

Upvotes: 1

Robert Harvey
Robert Harvey

Reputation: 180938

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.

Upvotes: 0

Related Questions