From 5b90fa1242e1da4af1e539a9d4699f922cf3a08c Mon Sep 17 00:00:00 2001 From: Kevin Matsubara Date: Mon, 14 Apr 2025 17:12:15 +0200 Subject: [PATCH] Override SaveChangesAsync to automatically add audit data. --- .../DeadBallZoneLeagueDbContext.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/EntityFrameworkCore.Data/DeadBallZoneLeagueDbContext.cs b/EntityFrameworkCore.Data/DeadBallZoneLeagueDbContext.cs index d5b6b93..fbeb099 100644 --- a/EntityFrameworkCore.Data/DeadBallZoneLeagueDbContext.cs +++ b/EntityFrameworkCore.Data/DeadBallZoneLeagueDbContext.cs @@ -42,6 +42,26 @@ public class DeadBallZoneLeagueDbContext : DbContext .HasName("GetEarliestMatch"); } + public override Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + var entries = ChangeTracker.Entries().Where( + λ => λ.State == EntityState.Modified || λ.State == EntityState.Added + ); + // Whenever a save is made to an entity, these fields are now automatically updated: + foreach (var entry in entries) + { + entry.Entity.ModifiedDate = DateTime.UtcNow; + entry.Entity.ModifiedBy = "Sample User 1"; + + if (entry.State == EntityState.Added) + { + entry.Entity.CreatedDate = DateTime.UtcNow; + entry.Entity.CreatedBy = "Sample User"; + } + } + return base.SaveChangesAsync(cancellationToken); + } + public DateTime GetEarliestTeamMatch(int teamId) => throw new NotImplementedException(); }