From af215be2454eb55261073cd0ccb90e25538e9281 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sun, 17 Nov 2024 12:24:42 +0200 Subject: [PATCH] Extends EF Core's automatic timestamp tracking to SaveChangesAsync --- .../Core/UoW/LuminaDbContext.cs | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index 0c07678e..e7c760bd 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -9,6 +9,8 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; using System; using System.Collections.Generic; using System.Linq; +using System.Threading; +using System.Threading.Tasks; #endregion namespace Lumina.DataAccess.Core.UoW; @@ -45,13 +47,37 @@ public class LuminaDbContext : DbContext base.OnModelCreating(modelBuilder); } - // TODO: implement async versions of SaveChanges - /// /// Overrides the SaveChanges method of the DbContext class to automatically set the Created and Updated properties of entities that implement the . /// /// The number of objects written to the underlying database. public override int SaveChanges() + { + HandleTimestamps(); + return base.SaveChanges(); + } + + /// + /// Overrides the SaveChangesAsync method of the DbContext class to automatically set the Created and Updated properties of entities that implement the . + /// + /// + /// A containing the number of objects written to the underlying database. + public override Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + HandleTimestamps(); + return base.SaveChangesAsync(cancellationToken); + } + + /// + /// Updates timestamp properties for tracked entities implementing based on their state in the change tracker. + /// + /// + /// + /// Created: Set for added entities. + /// Updated: Set for modified entities. + /// + /// + private void HandleTimestamps() { // get all the entity entries that are either added or modified IEnumerable entries = ChangeTracker.Entries() @@ -66,6 +92,5 @@ public class LuminaDbContext : DbContext else if (entityEntry.State == EntityState.Modified) ((IStorageEntity)entityEntry.Entity).Updated = DateTime.UtcNow; } - return base.SaveChanges(); } }