Entity Framework Core Interview Question #116

What is a savepoint in EF Core transactions?

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

Quick Interview Answer

A savepoint marks a point inside an existing transaction to which work can be rolled back without necessarily aborting the entire transaction.

Detailed Explanation

A savepoint marks a point inside an existing transaction to which work can be rolled back without necessarily aborting the entire transaction.

EF Core can use savepoints in certain SaveChanges scenarios when a transaction is already active, and applications can also work with transaction savepoint APIs where supported.

Provider capabilities vary, so savepoint behavior should be tested with the actual database used by the application.

Code Example

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

await tx.CreateSavepointAsync("BeforeInventory");

try
{
    await UpdateInventoryAsync();
    await db.SaveChangesAsync();
}
catch
{
    await tx.RollbackToSavepointAsync("BeforeInventory");
}