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







