ASP.NET Core Web API Interview Question #121
When should an API use database transactions?
Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate
Quick Interview Answer
Use a transaction when multiple database operations must succeed or fail as one atomic unit and the default SaveChanges transaction boundary is not sufficient. EF Core already wraps a single SaveChanges call in a transaction for providers that support transactions.
Detailed Explanation
Use a transaction when multiple database operations must succeed or fail as one atomic unit and the default SaveChanges transaction boundary is not sufficient. EF Core already wraps a single SaveChanges call in a transaction for providers that support transactions.
Avoid keeping transactions open while waiting on slow external network calls because long transactions can increase locking and contention.
Code Example
await using var transaction =
await _db.Database.BeginTransactionAsync(token);
try
{
// Multiple database operations
await _db.SaveChangesAsync(token);
await transaction.CommitAsync(token);
}
catch
{
await transaction.RollbackAsync(token);
throw;
}