Class EntityTimestampInterceptor
- Namespace
- Trellis.EntityFrameworkCore
- Assembly
- Trellis.EntityFrameworkCore.dll
EF Core SaveChanges interceptor that automatically sets CreatedAt and LastModified on entities before save.
public sealed class EntityTimestampInterceptor : SaveChangesInterceptor, ISaveChangesInterceptor, IInterceptor
- Inheritance
-
EntityTimestampInterceptor
- Implements
- Inherited Members
- Extension Methods
Remarks
CreatedAt is set once when the entity is first added (EntityState.Added)
and only if it has not already been set (preserves caller-supplied historical values for data migration).
LastModified is set on every save (EntityState.Added or EntityState.Modified).
For aggregate roots, LastModified is also updated when changes are detected in loaded child entities (tracked navigation properties) that are added, modified, or deleted — mirroring the promotion logic of Trellis.EntityFrameworkCore.AggregateETagInterceptor.
Registered automatically by AddTrellisInterceptors(DbContextOptionsBuilder).
Constructors
EntityTimestampInterceptor(TimeProvider?)
Initializes a new instance of the EntityTimestampInterceptor class.
public EntityTimestampInterceptor(TimeProvider? timeProvider = null)
Parameters
timeProviderTimeProviderThe time provider to use for timestamps. Defaults to System if
null.
Methods
SavingChanges(DbContextEventData, InterceptionResult<int>)
Sets timestamps on tracked entities before saving.
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
Parameters
eventDataDbContextEventDataThe event data associated with the current save operation.
resultInterceptionResult<int>The current interception result.
Returns
- InterceptionResult<int>
The interception result.
SavingChangesAsync(DbContextEventData, InterceptionResult<int>, CancellationToken)
Sets timestamps on tracked entities before saving asynchronously.
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
Parameters
eventDataDbContextEventDataThe event data associated with the current save operation.
resultInterceptionResult<int>The current interception result.
cancellationTokenCancellationTokenA token used to cancel the asynchronous save operation.
Returns
- ValueTask<InterceptionResult<int>>
The result of the asynchronous interception operation.