C# Interview Question #178

What are transactions in EF Core?

EF Core, Data Access & Performance Senior Advanced

Quick Interview Answer

A transaction ensures that a group of database operations succeeds or fails as a unit.

Detailed Explanation

A transaction ensures that a group of database operations succeeds or fails as a unit.

A single SaveChanges call is transactional for supported relational database providers when multiple changes need to be persisted. Explicit transactions are useful when multiple SaveChanges calls or other coordinated database operations must share the same transaction.

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

Code Example

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

try
{
    await _context.SaveChangesAsync();

    // Additional database work
    await _context.SaveChangesAsync();

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