XisongSpaceBooking_BackEnd/Configurations.cs
Chunyi 196a07ef9a 新增 ApplicationDbContext 並實現時間戳功能
新增 `ApplicationDbContext` 類別,繼承自 `DbContext`,並定義 `Departments`、`Roles` 和 `Accounts` 的 `DbSet` 屬性以管理實體。在 `OnModelCreating` 方法中應用相應的實體配置。覆寫 `SaveChanges` 和 `SaveChangesAsync` 方法,並新增 `ApplyTimestamps` 方法以自動設置實體的 `CreatedAt` 和 `UpdatedAt` 時間戳。
2025-09-26 16:36:56 +08:00

63 lines
1.8 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}
}
}