Entity Framework Core Interview Question #124
How can SaveChanges be customized for auditing fields?
Change Tracking, Updates, Transactions & Concurrency Mid-Level Intermediate
Quick Interview Answer
A DbContext can inspect tracked entries before SaveChanges and populate fields such as CreatedAtUtc and UpdatedAtUtc. This centralizes common persistence metadata instead of repeating it in every service.
Detailed Explanation
A DbContext can inspect tracked entries before SaveChanges and populate fields such as CreatedAtUtc and UpdatedAtUtc. This centralizes common persistence metadata instead of repeating it in every service.
Overrides should remain predictable and should not hide complex business behavior. User identity or request-specific data can be supplied through an appropriate abstraction rather than coupling the DbContext directly to controller state.
Interceptors are another option for cross-cutting persistence concerns.
Code Example
public override Task<int> SaveChangesAsync(
CancellationToken cancellationToken = default)
{
foreach (var entry in ChangeTracker
.Entries<IAuditableEntity>())
{
if (entry.State == EntityState.Added)
entry.Entity.CreatedAtUtc = DateTime.UtcNow;
if (entry.State == EntityState.Modified)
entry.Entity.UpdatedAtUtc = DateTime.UtcNow;
}
return base.SaveChangesAsync(cancellationToken);
}