liveBook · Manning

Rollback

As explained in .NET in Action, Second Edition

A rollback discards the changes made within a database transaction.

A rollback discards database changes made within a transaction. In a money transfer, crediting one account and debiting another must succeed together. A transaction prevents a failed debit from leaving the credit committed; the database can also roll back if the application loses its connection or crashes. section 11.2.1

An insufficient-funds transfer

Suppose both accounts start at 100. A transfer of 120 credits the recipient first, then fails when the sender cannot be debited. Without a transaction, the recipient’s credit remains. With a rollback, both database balances remain 100. section 11.2.1

Listing 11.11 A transactional version of the BankRepository.TransferAsync
public async Task TransferAsync(
  string from, string to, decimal amt)
{
  using var tx = await
    _ctxt.Database.BeginTransactionAsync();    #1
  
  try
  {
    await CreditAsync(to, amt);                #2
    await DebitAsync(from, amt);
    await tx.CommitAsync();                    #3
  }
  catch                                        #4
  {
    await tx.RollbackAsync();                  #5
    _ctxt.ChangeTracker.Clear();               #6
    throw;                                     #7
  }
}

The transactional TransferAsync starts a transaction, commits after both operations succeed, and calls RollbackAsync on failure. It then clears the EF Core change tracker so tracked entities do not retain the discarded changes. section 11.2.1

How .NET in Action, Second Edition covers it

How deep it goes
Works through transaction creation, commit, exception handling, rollback, and change-tracker cleanup in an asynchronous repository method.
Examples
Tests a transfer of 120 between accounts holding 100 each, then checks that both balances remain unchanged.
What it assumes
Assumes C# asynchronous methods and EF Core concepts while constructing the account, repository, and tests explicitly.
What you can do after
Apply it via EF Core transactions to reverse failed transfers and clear stale tracked state.
How it connects
Links rollback to database transactions, EF Core change tracking, exceptions, and atomic account updates.

Also explained in

Compare how 8 books explain rollback →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.