我对代码库进行了一些重构,并创建了一个抽象类SlottedHardware
,它包含了其他类应该使用的一些公共属性。
但是,我现在收到错误:
Schema specified is not valid. Errors: The relationship 'MyProject.Models.NetworkDevice_Slots' was not loaded because the type 'MyProject.Models.Models.NetworkDevice' is not available.
尝试通过将我的DbContext ctor设置为Database.SetInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>());
我已经在这里工作了几个小时,如果有人可以伸出援助之手,我将非常感激。以下是一些实体类,以及Fluent API映射:
public abstract class EntityBase
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
public abstract class SlottedHardware : EntityBase
{
public int MaxSlots { get; set; }
public virtual ICollection<Slot> Slots { get; set; }
}
public class Slot : EntityBase
{
public string SlotIdentifier { get; set; }
public List<Card> CompatibleCards { get; set; } = new List<Card>();
public State State { get; set; }
public virtual NetworkDevice NetworkDevice { get; set; }
}
public class NetworkDevice : SlottedHardware
{
public string Vendor { get; set; }
public string Model { get; set; }
public List<UnpublishedConfig> UnpublishedConfigs { get; set; }
public List<PublishedConfig> PublishedConfigs { get; set; }
public State State { get; set; }
/*** Constructors ***/
public NetworkDevice()
{
MaxSlots = 0;
Slots = new List<Slot>();
UnpublishedConfigs = new List<UnpublishedConfig>();
PublishedConfigs = new List<PublishedConfig>();
}
public NetworkDevice(string vendor, string model, int maxSlots) : this()
{
Vendor = vendor;
Model = model;
if(maxSlots > 0)
{
MaxSlots = maxSlots;
}
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// NetworkDevice entity
modelBuilder.Entity<NetworkDevice>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("NetworkDevices");
});
modelBuilder.Entity<NetworkDevice>().HasKey(t => t.Id);
modelBuilder.Entity<NetworkDevice>().
HasMany(t => t.Slots).
WithOptional(t => t.NetworkDevice);
modelBuilder.Entity<NetworkDevice>().
HasMany(t => t.PublishedConfigs).
WithMany();
modelBuilder.Entity<NetworkDevice>().
HasMany(t => t.UnpublishedConfigs).
WithMany();
modelBuilder.Entity<NetworkDevice>().Property(t => t.MaxSlots).IsRequired();
modelBuilder.Entity<NetworkDevice>().Property(t => t.Model).IsRequired();
// Slot entity
modelBuilder.Entity<Slot>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Slots");
});
modelBuilder.Entity<Slot>().HasKey(t => t.Id);
modelBuilder.Entity<Slot>().HasOptional(t => t.NetworkDevice).WithMany(x => x.Slots);
modelBuilder.Entity<Slot>().HasMany(t => t.CompatibleCards).WithMany(x => x.Slots);
modelBuilder.Entity<Slot>().Property(t => t.SlotIdentifier).IsRequired();
modelBuilder.Entity<Slot>().Ignore(t => t.Card);
}