ASP.NET Core Web API Interview Question #107

What is the Unit of Work pattern in relation to EF Core?

Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate

Quick Interview Answer

Unit of Work groups a set of changes so they can be committed as one logical operation. EF Core DbContext naturally performs this role by tracking changes and persisting them through SaveChanges or SaveChangesAsync.

Detailed Explanation

Unit of Work groups a set of changes so they can be committed as one logical operation. EF Core DbContext naturally performs this role by tracking changes and persisting them through SaveChanges or SaveChangesAsync.

A separate UnitOfWork abstraction can be useful in some architectures, but it should provide real value rather than simply rename DbContext methods.

Code Example

await db.Orders.AddAsync(order, token);
db.AuditEntries.Add(audit);

await db.SaveChangesAsync(token);