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