From 196a07ef9a906f3895b9920d3d5262d1a1bd9f48 Mon Sep 17 00:00:00 2001 From: Chunyi Date: Fri, 26 Sep 2025 16:36:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20ApplicationDbContext=20?= =?UTF-8?q?=E4=B8=A6=E5=AF=A6=E7=8F=BE=E6=99=82=E9=96=93=E6=88=B3=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 `ApplicationDbContext` 類別,繼承自 `DbContext`,並定義 `Departments`、`Roles` 和 `Accounts` 的 `DbSet` 屬性以管理實體。在 `OnModelCreating` 方法中應用相應的實體配置。覆寫 `SaveChanges` 和 `SaveChangesAsync` 方法,並新增 `ApplyTimestamps` 方法以自動設置實體的 `CreatedAt` 和 `UpdatedAt` 時間戳。 --- Configurations.cs | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Configurations.cs diff --git a/Configurations.cs b/Configurations.cs new file mode 100644 index 0000000..f182db6 --- /dev/null +++ b/Configurations.cs @@ -0,0 +1,63 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Models.Entities; +using Configurations; + +public class ApplicationDbContext : DbContext +{ + public ApplicationDbContext(DbContextOptions options) + : base(options) + { + } + + public DbSet Departments => Set(); + public DbSet Roles => Set(); + public DbSet Accounts => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + // MΩҦ EntityTypeConfiguration + modelBuilder.ApplyConfiguration(new DepartmentConfiguration()); + modelBuilder.ApplyConfiguration(new RoleConfiguration()); + modelBuilder.ApplyConfiguration(new AccountConfiguration()); + } + + public override int SaveChanges() + { + ApplyTimestamps(); + return base.SaveChanges(); + } + + public override Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + ApplyTimestamps(); + return base.SaveChangesAsync(cancellationToken); + } + + private void ApplyTimestamps() + { + var utcNow = DateTime.UtcNow; + + foreach (var entry in ChangeTracker.Entries()) + { + switch (entry.State) + { + case EntityState.Added: + entry.Entity.CreatedAt = utcNow; + entry.Entity.UpdatedAt = null; + break; + + case EntityState.Modified: + // קKק CreatedAt + entry.Property(e => e.CreatedAt).IsModified = false; + entry.Entity.UpdatedAt = utcNow; + break; + } + } + } +} \ No newline at end of file