using System.Linq.Expressions; using Microsoft.EntityFrameworkCore; using MilliSim.Common.Entities; namespace MilliSim.Data; public class MilliSimDbContext : DbContext { public MilliSimDbContext(DbContextOptions options) : base(options) { } public DbSet Users => Set(); public DbSet Projects => Set(); public DbSet ProjectCategories => Set(); public DbSet PlatformTypes => Set(); public DbSet FeatureTags => Set(); public DbSet ProjectTagRelations => Set(); public DbSet ProjectScreenshots => Set(); public DbSet ProjectPackages => Set(); public DbSet Favorites => Set(); public DbSet ExperienceLogs => Set(); public DbSet Authorizations => Set(); public DbSet Banners => Set(); public DbSet Partners => Set(); public DbSet Consultations => Set(); public DbSet Notifications => Set(); public DbSet NotificationReads => Set(); public DbSet OperationLogs => Set(); public DbSet SystemSettings => Set(); public DbSet Backups => Set(); public DbSet WakeProtocols => Set(); public DbSet PendingUploads => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 软删除全局过滤器 foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { if (typeof(BaseEntity).IsAssignableFrom(entityType.ClrType)) { var parameter = Expression.Parameter(entityType.ClrType, "e"); var property = Expression.Property(parameter, nameof(BaseEntity.IsDeleted)); var falseValue = Expression.Constant(false); var comparison = Expression.Equal(property, falseValue); var lambda = Expression.Lambda(comparison, parameter); modelBuilder.Entity(entityType.ClrType).HasQueryFilter((dynamic)lambda); } } // 唯一索引 modelBuilder.Entity().HasIndex(u => u.Username).IsUnique(); modelBuilder.Entity().HasIndex(s => s.Key).IsUnique(); // PendingUpload 索引(用于垃圾资源清理查询) modelBuilder.Entity().HasIndex(p => p.ObjectKey); modelBuilder.Entity().HasIndex(p => p.ConsumedAt); // 字符集 modelBuilder.Entity().Property(p => p.Content).HasColumnType("longtext"); // 精度 foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { foreach (var property in entityType.GetProperties()) { if (property.ClrType == typeof(DateTime)) { property.SetColumnType("datetime"); } } } } }