#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Core.UoW; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using System; using System.Threading; using System.Threading.Tasks; #endregion namespace Lumina.DataAccess.Common.Interceptors; /// /// Interceptor for updating audit fields automatically for entities implementing . /// public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor { private readonly ICurrentUserService _currentUserService; private readonly IDateTimeProvider _dateTimeProvider; /// /// Initializes a new instance of the class. /// /// Injected service to retrieve the current user information. /// Injected service for time related functionality. public UpdateAuditableEntitiesInterceptor(ICurrentUserService currentUserService, IDateTimeProvider dateTimeProvider) { _currentUserService = currentUserService; _dateTimeProvider = dateTimeProvider; } /// /// Intercepts the synchronous SaveChanges operation to update audit fields. /// /// The event data containing the . /// The result of the SaveChanges operation. /// The interception result. public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) { UpdateAuditableEntities(eventData.Context); return base.SavingChanges(eventData, result); } /// /// Intercepts the asynchronous SaveChangesAsync operation to update audit fields. /// /// The event data containing the . /// The result of the SaveChanges operation. /// Cancellation token that can be used to stop the execution. /// A containing the interception result. public override ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { UpdateAuditableEntities(eventData.Context); return base.SavingChangesAsync(eventData, result, cancellationToken); } /// /// Updates the audit fields for all changed entities that implement IAuditableEntity. /// /// The containing the entities to update. private void UpdateAuditableEntities(DbContext? context) { if (context is null) return; // Initialization is the one save whose audit identity is provided explicitly, because no user account exists yet. if (context is LuminaDbContext luminaDbContext && luminaDbContext.IsInitializationSave) return; Guid? userId = _currentUserService.UserId; DateTime utcNow = _dateTimeProvider.UtcNow; // Retrieve all entities implementing IAuditableEntity that are being tracked and have either Added or Modified state. foreach (EntityEntry entry in context.ChangeTracker.Entries()) { if (entry.State == EntityState.Added) SetCreationProperties(entry.Entity, userId, utcNow); else if(entry.State == EntityState.Modified) SetModificationProperties(entry, userId, utcNow); } } /// /// Sets the creation audit properties for a newly added entity. /// /// The entity being created. /// The unique identifier of the user creating the entity. /// The current UTC timestamp. private static void SetCreationProperties(IAuditableEntity entity, Guid? userId, DateTime utcNow) { entity.CreatedOnUtc = utcNow; entity.CreatedBy = userId ?? default; entity.UpdatedOnUtc = null; entity.UpdatedBy = null; } /// /// Sets the modification audit properties for an updated entity while protecting creation properties. /// /// The entity entry being modified. /// The unique identifier of the user modifying the entity. /// The current UTC timestamp. private static void SetModificationProperties(EntityEntry entry, Guid? userId, DateTime utcNow) { // Prevent modification of creation properties. entry.Property(auditableEntity => auditableEntity.CreatedOnUtc).IsModified = false; entry.Property(auditableEntity => auditableEntity.CreatedBy).IsModified = false; // Set modification properties. entry.Entity.UpdatedOnUtc = utcNow; entry.Entity.UpdatedBy = userId ?? default; } }