Sub topic 17
Working with Transactions
Some tasks need several database changes to happen together. Picture a bank transfer: you take money out of one account and put it into another. If the first step works and the second fails, the money is gone. This chapter shows how EF Core groups changes so they all succeed or none of them do.
What a Transaction Is
A transaction is a group of database operations that the database treats as one unit. It ends in one of two ways:
- Commit means "keep everything." All the changes become permanent at once.
- Rollback means "undo everything." The database returns to how it was before the transaction started.
Database people say a transaction is atomic. Atomic means it cannot be split. Other users never see a half-finished transaction.
SaveChanges Already Uses a Transaction
You have been using transactions without knowing it. Each call to SaveChangesAsync wraps all of its changes in a transaction automatically.
using var db = new BloggingContext();
db.Blogs.Add(new Blog { Url = "https://example.com/one" });
db.Blogs.Add(new Blog { Url = "https://example.com/two" });
// Both inserts are sent inside one transaction.
// If the second insert fails, the first is undone too.
await db.SaveChangesAsync();So when all your changes go through one SaveChangesAsync call, you do not need to do anything extra. This covers most everyday code.
When You Need an Explicit Transaction
Sometimes one SaveChangesAsync call is not enough. Common cases:
- You need a value that the database creates, like a new
BlogId, before you can build the next change. - You mix
SaveChangesAsyncwith bulk methods such asExecuteUpdateAsyncorExecuteDeleteAsync. Those bulk methods run right away and do not join theSaveChangesAsynctransaction. - You run raw SQL commands next to normal EF Core changes.
In these cases you start a transaction yourself with db.Database.BeginTransactionAsync().
Your First Explicit Transaction
This code uses the BloggingContext, Blog, and Post classes from earlier chapters.
using var db = new BloggingContext();
using var transaction = await db.Database.BeginTransactionAsync();
db.Blogs.Add(new Blog { Url = "https://example.com/a" });
await db.SaveChangesAsync();
db.Blogs.Add(new Blog { Url = "https://example.com/b" });
await db.SaveChangesAsync();
await transaction.CommitAsync();Here is what happens, step by step:
BeginTransactionAsyncopens a transaction on the database connection.- The first
SaveChangesAsyncinserts blog "a". It joins your transaction instead of making its own, so the insert is not permanent yet. - The second
SaveChangesAsyncinserts blog "b" inside the same transaction. CommitAsyncmakes both inserts permanent together.
What if the code throws an error before CommitAsync? The using statement disposes the transaction. Dispose means "clean up and release." A transaction that is disposed without a commit rolls back. Both inserts disappear.
Handling Errors with Rollback
Relying on dispose works. Many teams still like to write the rollback out so the intent is clear. The pattern looks like this:
using var db = new BloggingContext();
await using var transaction = await db.Database.BeginTransactionAsync();
try
{
var blog = new Blog { Url = "https://example.com/news" };
db.Blogs.Add(blog);
await db.SaveChangesAsync();
// blog.BlogId now holds the id the database created.
db.Posts.Add(new Post
{
Title = "Welcome",
Content = "First post",
BlogId = blog.BlogId
});
await db.SaveChangesAsync();
await transaction.CommitAsync();
}
catch (Exception)
{
await transaction.RollbackAsync();
throw;
}The throw; line passes the error on after the rollback, so the problem is not hidden.
Seeing a Rollback Happen
Run this program to watch a rollback in action. It needs the BloggingContext from earlier chapters in the same project.
using Microsoft.EntityFrameworkCore;
bool simulateFailure = true;
using (var countDb = new BloggingContext())
{
Console.WriteLine($"Blogs before: {await countDb.Blogs.CountAsync()}");
}
try
{
using var db = new BloggingContext();
using var transaction = await db.Database.BeginTransactionAsync();
db.Blogs.Add(new Blog { Url = "https://example.com/temp" });
await db.SaveChangesAsync();
Console.WriteLine("Blog saved inside the transaction.");
if (simulateFailure)
{
throw new InvalidOperationException("Something went wrong.");
}
await transaction.CommitAsync();
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
using (var countDb = new BloggingContext())
{
Console.WriteLine($"Blogs after: {await countDb.Blogs.CountAsync()}");
}The "before" and "after" counts match. The blog was saved inside the transaction but never committed, so the database threw it away. Change simulateFailure to false and run it again. Now the count goes up by one.
Mixing Bulk Operations into a Transaction
Bulk methods run immediately and skip the change tracker. Put them in an explicit transaction when they must succeed or fail together with other changes.
using var db = new BloggingContext();
await using var transaction = await db.Database.BeginTransactionAsync();
int archived = await db.Posts
.Where(p => p.BlogId == 1)
.ExecuteUpdateAsync(s => s.SetProperty(p => p.Title, p => p.Title + " (archived)"));
db.Blogs.Add(new Blog { Url = "https://example.com/archive-notice" });
await db.SaveChangesAsync();
await transaction.CommitAsync();
Console.WriteLine($"Archived {archived} posts.");If adding the new blog fails, the title changes are rolled back too.
Quick Reference
| Method | What it does |
|---|---|
| `SaveChangesAsync()` | Saves all tracked changes inside its own transaction, or joins one you started |
| `Database.BeginTransactionAsync()` | Starts an explicit transaction |
| `transaction.CommitAsync()` | Makes every change in the transaction permanent |
| `transaction.RollbackAsync()` | Undoes every change in the transaction |
| Disposing without commit | Rolls back automatically |
Common Mistakes
- Forgetting to commit. If you never call
CommitAsync, nothing is kept. Your code seems to work, but the data is gone. - Keeping a transaction open too long. An open transaction can block other users from changing the same rows. Never wait for user input, a slow web request, or a timer while a transaction is open. Do the work, then commit quickly.
- Using an explicit transaction when one SaveChanges would do. This adds code and gains nothing.
- Reusing a context after a failure. As the warning above says, create a fresh context instead.
Exercises
Exercise
You add three new posts to the context and then call SaveChangesAsync once. The third insert fails. How many of the three posts are in the database afterward, and why?
Show answer
Zero. A single SaveChangesAsync call wraps all its changes in one transaction, so when the third insert fails, the first two are rolled back as well.
Exercise
A developer starts a transaction, calls SaveChangesAsync twice, and the method returns without calling CommitAsync. No exception was thrown. What happens to the data?
Show answer
It is lost. When the transaction is disposed at the end of the using block without a commit, it rolls back, so neither SaveChangesAsync call's changes are kept.
Exercise
Why might you need an explicit transaction when combining ExecuteDeleteAsync with SaveChangesAsync, even though SaveChangesAsync already uses a transaction?
Show answer
ExecuteDeleteAsync runs right away as its own command and does not join the transaction that SaveChangesAsync creates. Without an explicit transaction, the delete could succeed while the later SaveChangesAsync fails, which leaves the data half-changed.
Exercise
Edit the "Seeing a Rollback Happen" program so that it adds two blogs, each with its own SaveChangesAsync call, before the simulated failure. Predict the before and after counts, then run it to check.
Show answer
The before and after counts are still equal. Both inserts happen inside the same uncommitted transaction, so the rollback removes both of them.