-
-
Notifications
You must be signed in to change notification settings - Fork 602
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support EF interceptors #1591
Comments
Hello @rezathecoder if you are using the |
Can you please guide me so i can imlplement that? |
below is an example of doing work before saving the entries. for after saving the entries, you have to override the public sealed class NonQueryAuditableEntityInterceptor : DbCommandInterceptor
{
private readonly ILogger<NonQueryAuditableEntityInterceptor> _logger;
private readonly TimeProvider _timeProvider;
public NonQueryAuditableEntityInterceptor(ILogger<NonQueryAuditableEntityInterceptor> logger, TimeProvider timeProvider)
{
_logger = logger;
_timeProvider = timeProvider;
}
public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
{
if (eventData.Context is not null)
{
UpdateAuditableEntities(eventData.Context);
}
return base.NonQueryExecuting(command, eventData, result);
}
public override ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
if (eventData.Context is not null)
{
UpdateAuditableEntities(eventData.Context);
}
return base.NonQueryExecutingAsync(command, eventData, result, cancellationToken);
}
private void UpdateAuditableEntities(DbContext context)
{
var utcNow = _timeProvider.GetUtcNow().UtcDateTime;
var changeTracker = context.ChangeTracker;
changeTracker.DetectChanges();
var entityEntries = changeTracker.Entries<IAuditableEntity>().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified).ToList();
foreach (var entityEntry in entityEntries)
{
switch (entityEntry.State)
{
case EntityState.Added:
SetCurrentPropertyValue(entityEntry, nameof(IAuditableEntity.CreatedOnUtc), utcNow);
break;
case EntityState.Modified:
SetCurrentPropertyValue(entityEntry, nameof(IAuditableEntity.ModifiedOnUtc), utcNow);
break;
}
}
return;
static void SetCurrentPropertyValue(EntityEntry entry, string propertyName, DateTime utcNow) => entry.Property(propertyName).CurrentValue = utcNow;
}
}
public interface IAuditableEntity
{
DateTime CreatedOnUtc { get; }
DateTime? ModifiedOnUtc { get; }
} *** Remember to add the Interceptor in your |
Hi |
@ArtemMaslow I have no idea. |
@rezathecoder one way to add some custom logic would be to override BulkMethods you use as explained here: Regarding Interceptors here is some useful info: |
Hi
Is it possible to support EF interceptors when using BulkSaveChanges ?
@borisdj
The text was updated successfully, but these errors were encountered: