Entity Framework Core Interview Question #114

Does SaveChanges use a transaction automatically?

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

Quick Interview Answer

For relational databases that support transactions, EF Core normally wraps the changes in a single SaveChanges call in a transaction. If a command fails, the transaction can roll back so the group of changes is not partially committed.

Detailed Explanation

For relational databases that support transactions, EF Core normally wraps the changes in a single SaveChanges call in a transaction. If a command fails, the transaction can roll back so the group of changes is not partially committed.

This means an explicit transaction is unnecessary for many simple unit-of-work operations.

An explicit transaction becomes useful when several SaveChanges calls or other coordinated database operations must share the same transaction boundary.

Code Example

db.Orders.Add(order);
db.OrderItems.AddRange(items);

// Normally committed atomically as one SaveChanges unit.
await db.SaveChangesAsync();