using AmtScanner.Api.Models; using Microsoft.EntityFrameworkCore; namespace AmtScanner.Api.Data; public class AppDbContext : DbContext { public AppDbContext(DbContextOptions options) : base(options) { } public DbSet AmtDevices { get; set; } public DbSet AmtCredentials { get; set; } public DbSet HardwareInfos { get; set; } public DbSet MemoryModules { get; set; } public DbSet StorageDevices { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 限制索引字段长度以适应 MySQL modelBuilder.Entity() .Property(d => d.IpAddress) .HasMaxLength(50); modelBuilder.Entity() .HasIndex(d => d.IpAddress) .IsUnique(); modelBuilder.Entity() .Property(c => c.Name) .HasMaxLength(200); modelBuilder.Entity() .HasIndex(c => c.Name); // HardwareInfo 配置 modelBuilder.Entity() .HasOne(h => h.Device) .WithMany() .HasForeignKey(h => h.DeviceId) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity() .HasIndex(h => h.DeviceId); modelBuilder.Entity() .HasIndex(h => h.LastUpdated); // MemoryModule 配置 modelBuilder.Entity() .HasOne(m => m.HardwareInfo) .WithMany(h => h.MemoryModules) .HasForeignKey(m => m.HardwareInfoId) .OnDelete(DeleteBehavior.Cascade); // StorageDevice 配置 modelBuilder.Entity() .HasOne(s => s.HardwareInfo) .WithMany(h => h.StorageDevices) .HasForeignKey(s => s.HardwareInfoId) .OnDelete(DeleteBehavior.Cascade); } }