using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using TakeoutSaaS.Domain.Dictionary.Entities; using TakeoutSaaS.Infrastructure.Common.Persistence; using TakeoutSaaS.Shared.Abstractions.Security; using TakeoutSaaS.Shared.Abstractions.Tenancy; namespace TakeoutSaaS.Infrastructure.Dictionary.Persistence; /// /// 参数字典 DbContext。 /// public sealed class DictionaryDbContext( DbContextOptions options, ITenantProvider tenantProvider, ICurrentUserAccessor? currentUserAccessor = null) : TenantAwareDbContext(options, tenantProvider, currentUserAccessor) { /// /// 字典分组集。 /// public DbSet DictionaryGroups => Set(); /// /// 字典项集。 /// public DbSet DictionaryItems => Set(); /// /// 配置实体模型。 /// /// 模型构建器。 protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); ConfigureGroup(modelBuilder.Entity()); ConfigureItem(modelBuilder.Entity()); ApplyTenantQueryFilters(modelBuilder); } /// /// 配置字典分组。 /// /// 实体构建器。 private static void ConfigureGroup(EntityTypeBuilder builder) { builder.ToTable("dictionary_groups"); builder.HasKey(x => x.Id); builder.Property(x => x.TenantId).IsRequired(); builder.Property(x => x.Code).HasMaxLength(64).IsRequired(); builder.Property(x => x.Name).HasMaxLength(128).IsRequired(); builder.Property(x => x.Scope).HasConversion().IsRequired(); builder.Property(x => x.Description).HasMaxLength(512); builder.Property(x => x.IsEnabled).HasDefaultValue(true); ConfigureAuditableEntity(builder); ConfigureSoftDeleteEntity(builder); builder.HasIndex(x => x.TenantId); builder.HasIndex(x => new { x.TenantId, x.Code }).IsUnique(); } /// /// 配置字典项。 /// /// 实体构建器。 private static void ConfigureItem(EntityTypeBuilder builder) { builder.ToTable("dictionary_items"); builder.HasKey(x => x.Id); builder.Property(x => x.TenantId).IsRequired(); builder.Property(x => x.GroupId).IsRequired(); builder.Property(x => x.Key).HasMaxLength(64).IsRequired(); builder.Property(x => x.Value).HasMaxLength(256).IsRequired(); builder.Property(x => x.Description).HasMaxLength(512); builder.Property(x => x.SortOrder).HasDefaultValue(100); builder.Property(x => x.IsEnabled).HasDefaultValue(true); ConfigureAuditableEntity(builder); ConfigureSoftDeleteEntity(builder); builder.HasOne(x => x.Group) .WithMany(g => g.Items) .HasForeignKey(x => x.GroupId) .OnDelete(DeleteBehavior.Cascade); builder.HasIndex(x => x.TenantId); builder.HasIndex(x => new { x.GroupId, x.Key }).IsUnique(); } }