Entity Framework Core Interview Question #113

What is a transaction in EF Core?

Change Tracking, Updates, Transactions & Concurrency Mid-Level Intermediate

Quick Interview Answer

A database transaction groups operations into a unit that either commits successfully or is rolled back. Transactions protect consistency when multiple related database changes must succeed together.

Detailed Explanation

A database transaction groups operations into a unit that either commits successfully or is rolled back. Transactions protect consistency when multiple related database changes must succeed together.

For relational providers, a single SaveChanges call is normally transactional when the provider supports transactions. Explicit transactions are useful when a business operation spans multiple SaveChanges calls or additional database operations.

Transactions should be kept as short as practical to reduce locking and contention.

Code Example

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

try
{
    // Multiple database operations
    await db.SaveChangesAsync();

    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}