66 lines
2.1 KiB
C#

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