Entity Framework Core Interview Question #115

How do you create an explicit transaction in EF Core?

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

Quick Interview Answer

Use Database.BeginTransaction or BeginTransactionAsync to create a transaction. Perform the required operations, then explicitly commit. If an exception occurs before commit, roll back or allow disposal to end the uncommitted transaction according to provider behavior.

Detailed Explanation

Use Database.BeginTransaction or BeginTransactionAsync to create a transaction. Perform the required operations, then explicitly commit. If an exception occurs before commit, roll back or allow disposal to end the uncommitted transaction according to provider behavior.

Keep the transaction scope focused and avoid slow external network calls while database locks are held.

When retrying transient failures, transaction handling should be coordinated with the configured execution strategy.

Code Example

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

await CreateOrderAsync();
await db.SaveChangesAsync(cancellationToken);

await ReserveInventoryAsync();
await db.SaveChangesAsync(cancellationToken);

await tx.CommitAsync(cancellationToken);