新增 `ApplicationDbContext` 類別,繼承自 `DbContext`,並定義 `Departments`、`Roles` 和 `Accounts` 的 `DbSet` 屬性以管理實體。在 `OnModelCreating` 方法中應用相應的實體配置。覆寫 `SaveChanges` 和 `SaveChangesAsync` 方法,並新增 `ApplyTimestamps` 方法以自動設置實體的 `CreatedAt` 和 `UpdatedAt` 時間戳。
63 lines
1.8 KiB
C#
63 lines
1.8 KiB
C#
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;
|
||
}
|
||
}
|
||
}
|
||
} |