新增 ApplicationDbContext 並實現時間戳功能

新增 `ApplicationDbContext` 類別,繼承自 `DbContext`,並定義 `Departments`、`Roles` 和 `Accounts` 的 `DbSet` 屬性以管理實體。在 `OnModelCreating` 方法中應用相應的實體配置。覆寫 `SaveChanges` 和 `SaveChangesAsync` 方法,並新增 `ApplyTimestamps` 方法以自動設置實體的 `CreatedAt` 和 `UpdatedAt` 時間戳。
This commit is contained in:
Chen, Chun-Yi 2025-09-26 16:36:56 +08:00
parent 194609720a
commit 196a07ef9a

63
Configurations.cs Normal file
View File

@ -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<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Department> Departments => Set<Department>();
public DbSet<Role> Roles => Set<Role>();
public DbSet<Account> Accounts => Set<Account>();
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<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
ApplyTimestamps();
return base.SaveChangesAsync(cancellationToken);
}
private void ApplyTimestamps()
{
var utcNow = DateTime.UtcNow;
foreach (var entry in ChangeTracker.Entries<BaseEntity>())
{
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;
}
}
}
}