public class abstract Animal
{
[Key]
public string AnimalId { get; set; }
public Zoo Zoo { get; set; }
public string ZooId { get; set; }
}
public class Giraffe : Animal { }
public class Elephant : Animal { }
public class Zoo
{
[Key]
public string ZooId { get; set; }
public ICollection<Giraffe> Giraffes { get; set; }
public ICollection<Elephant> Elephants { get; set; }
}
//OnModelCreating
builder.Entity<Animal>.HasOne(a => a.Zoo).WithMany().HasForeignKey(a => a.ZooId); //1
builder.Entity<Giraffe>.HasOne(g => g.Zoo).WithMany(z => Giraffes).HasForeignKey(g => g.ZooId); //2
builder.Entity<Elephant>.HasOne(g => g.Zoo).WithMany(z => Elephants ).HasForeignKey(g => g.ZooId); //3
//DbSets
public DbSet<Animal> Animals { get; set; }
public DbSet<Giraffe> Giraffes { get; set; }
public DbSet<Elephant> Elephants { get; set; }
public DbSet<Zoo> Zoos { get; set; }
我在这里收到错误:
导航属性&#39; Giraffes&#39;无法添加到实体类型 &#39;动物园&#39;因为它的CLR类型ICollection Giraffe&gt;不符合 预期的CLR类型&#39; Animal&#39;。
可以通过替换 1
来修复builder.Entity<Animal>.Ignore(a => a.Zoo);
//both 2 and 3 here
然而它有一个非常严重的副作用:
await DbContextInstance.Animals.Include(a => a.Zoo).ToListAsync(); //Include throws ArgumentNullException
我可以解决此问题,而无需将ICollection<Giraffe> Giraffes
和ICollection<Elephant> Elephants
联合到ICollection<Animal> Animals
吗?