Sub topic 17
Working with Transactions
Sometimes several changes must succeed together or fail together. Moving money between two accounts is the classic case. A transaction is a group of database changes that the database treats as one unit. Either all of them are saved, or none are.
SaveChanges Already Uses a Transaction
Each call to SaveChangesAsync runs inside its own transaction. If you add three blogs and call it once, EF Core saves all three or none of them. You only need an explicit transaction when your work spans more than one SaveChangesAsync call.
An Explicit Transaction
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();BeginTransactionAsync starts the transaction. CommitAsync makes the changes permanent. If an exception happens before the commit, the using statement disposes the transaction, and that rolls back both inserts. Rollback means the database undoes every change made in the transaction.
Handling Concurrency Conflicts
A concurrency conflict happens when two users load the same row, and both change it. Without protection, the second save silently overwrites the first one. This is called a "lost update."
EF Core uses optimistic concurrency. It doesn't lock rows ahead of time. It checks at save time whether someone else changed the row first.
Adding a Concurrency Token
A concurrency token is a property that EF Core checks before it updates a row. Mark it with [ConcurrencyCheck]:
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
public class Product
{
public int Id { get; set; }
public decimal Price { get; set; }
[ConcurrencyCheck]
public int Version { get; set; }
}When you save, EF Core adds the token's original value to the SQL WHERE clause, like WHERE Id = 1 AND Version = 3. If another writer already changed Version, no row matches. EF Core sees that zero rows were updated and throws DbUpdateConcurrencyException.
Catching the Conflict
var product = await db.Products.FirstAsync(p => p.Id == 1);
try
{
product.Price = 19.99m;
product.Version++;
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
foreach (var entry in ex.Entries)
{
await entry.ReloadAsync();
}
}ReloadAsync replaces the entity's values with the current values from the database. After that, you can show the new data to the user or try the change again.
Exercise
You call SaveChangesAsync once after adding five posts. Do you need an explicit transaction to make sure all five are saved together?
Show answer
No. A single SaveChangesAsync call already runs in its own transaction, so either all five posts are saved or none are. You need an explicit transaction only when the work spans more than one SaveChangesAsync call.
Exercise
Why does EF Core throw DbUpdateConcurrencyException when another user changed the row first?
Show answer
EF Core puts the original Version value in the UPDATE's WHERE clause. The other user already changed Version, so no row matches and zero rows are updated. EF Core treats that as a conflict and throws the exception.