SQL Server Interview Question #290

How does EF Core handle transactions?

ASP.NET Core, EF Core & SQL Server Real-World Scenarios Senior Advanced

Detailed Explanation

SaveChanges automatically uses a transaction when required so the changes in that call are committed atomically. EF Core also supports explicit transactions for operations that must span multiple SaveChanges calls or database steps.

Explicit transaction scope should remain short. Do not hold a database transaction open while waiting for user input, calling slow external APIs, or performing unrelated work.

For retrying execution strategies, transaction handling must follow EF Core's supported pattern so the entire transaction can be retried safely when appropriate.

Code Example

await using var tx = await db.Database.BeginTransactionAsync();

try
{
    // Database operations
    await db.SaveChangesAsync();
    await tx.CommitAsync();
}
catch
{
    await tx.RollbackAsync();
    throw;
}