using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Models.Entities; namespace Configurations { public class AccountConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { builder.ToTable("accounts"); builder.HasKey(a => a.AccountId); builder.Property(a => a.AccountId) .HasColumnName("account_id"); builder.Property(a => a.Name) .HasColumnName("name") .IsRequired() .HasMaxLength(100); builder.Property(a => a.Username) .HasColumnName("username") .IsRequired() .HasMaxLength(50); builder.Property(a => a.Password) .HasColumnName("password") .IsRequired() .HasMaxLength(256); builder.Property(a => a.Email) .HasColumnName("email") .IsRequired() .HasMaxLength(254); builder.Property(a => a.DepartmentId) .HasColumnName("department_id") .IsRequired(); builder.Property(a => a.RoleId) .HasColumnName("role_id") .IsRequired(); builder.Property(a => a.Status) .HasColumnName("status") .HasConversion() .IsRequired() .HasMaxLength(20); builder.Property(a => a.CreatedAt) .HasColumnName("created_at") .IsRequired(); builder.Property(a => a.UpdatedAt) .HasColumnName("updated_at"); builder.Property(a => a.ModifiedBy) .HasColumnName("modified_by"); // 唯一索引 builder.HasIndex(a => a.Username) .IsUnique() .HasDatabaseName("UX_accounts_username"); builder.HasIndex(a => a.Email) .IsUnique() .HasDatabaseName("UX_accounts_email"); // 關聯與刪除行為 builder.HasOne(a => a.Department) .WithMany(d => d.Accounts) .HasForeignKey(a => a.DepartmentId) .OnDelete(DeleteBehavior.Restrict); builder.HasOne(a => a.Role) .WithMany(r => r.Accounts) .HasForeignKey(a => a.RoleId) .OnDelete(DeleteBehavior.Restrict); // 自參照外鍵:modified_by -> accounts.account_id (SET NULL) builder.HasOne() .WithMany() .HasForeignKey(a => a.ModifiedBy) .OnDelete(DeleteBehavior.SetNull); } } }