using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using MultiTenancySample.FieldIsolationService.Entities; using MultiTenancySample.ServiceDefaults; namespace MultiTenancySample.FieldIsolationService.EntityFrameworks { public class TenantSaveChangesInterceptor(ICurrentTenant currentTenant) : SaveChangesInterceptor { public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) { if (eventData.Context is not null) { MultiTenancyTracking(eventData.Context); } return base.SavingChanges(eventData, result); } public override ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { if (eventData.Context is not null) { MultiTenancyTracking(eventData.Context); } return base.SavingChangesAsync(eventData, result, cancellationToken); } private void MultiTenancyTracking(DbContext dbContext) { IEnumerable> multiTenancyEntries = dbContext.ChangeTracker.Entries().Where(entry => entry.State == EntityState.Added || entry.State == EntityState.Modified); multiTenancyEntries?.ToList().ForEach(entityEntry => { entityEntry.Entity.TenantId ??= currentTenant.TenantId; }); } } }