TPT inheritance with Abstract base doesn't reference children in related table

135 Views Asked by At

I'm struggling with TPT inheritance in MVC - EF.

I have an AAnimal abstract class and two classes that inherit it, Zebra and Lion. There is a Cage class which holds an AAnimal.

My problem is that because AAnimal is abstract, the EF cannot create an instance of it when I load all Cages. So what I want is a way to override this behavior and make it understand whether it needs to load a Zebra or a Lion.

Zebra and Lion have a Primary key which is also foreign key to Animal table. This is done by the EF (TPT inheritance model).

public abstract class AAnimal
{
    [Key]
    public int AnimalId { set; get; }
    public string Name { set; get; }
}

public class Lion : AAnimal {}
public class Zebra : AAnimal {}

public class Εmployee
{
    [Key]
    public int EmployeeId { set; get; }
    public string Name { set; get; }
}

public class Cage
{
    [Key]
    public int CageId { set; get; }

    [ForeignKey("CagedAnimal")]
    public int CagedAnimalId { set; get; }
    public AAnimal CagedAnimal { set; get; }

    [ForeignKey("CageEmployee")]
    public int CageEmployeeId { set; get; }
    public Employee CageEmployee { set; get; }
}

// Model mapping
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<AAnimal>().ToTable("Animal");
    modelBuilder.Entity<Lion>().ToTable("Lion");
    modelBuilder.Entity<Zebra>().ToTable("Zebra");
    modelBuilder.Entity<Εmployee>().ToTable("Εmployee");
}

// Load all cages
public ActionResult Index()
{
    var allCages = db.Cages.ToList();
}

At this point all cages are loaded, all fields have values except the CagedAnimal which is null. Even the CagedAnimalId has value.

How can I tell the EF to follow the same procedure while saving data, in order to load entities?

Note that this is just an example. Also, TPT inheritance model has been selected over other inheritance models.

0

There are 0 best solutions below