Search code examples
c#entity-frameworkmultiple-inheritancetable-per-type

Multilevel inheritance using TPT design in Entity Framework


I want to implement the following model in EF as TPT design.

enter image description here

My codes are as follows:

Base model

public abstract class Product
{
    public int Id { get; set; }
    public DateTime ProductionDate { get; set; }
}

Car models

public abstract class Car : Product
{
    public string ChassisNumber { get; set; }
    public string DriverName { get; set; }
}

[Table("TeslaCars")]
public class TeslaCar : Car
{
    public string Battery { get; set; }
    public int Temperature { get; set; }
}

[Table("PorscheCars")]
public class PorscheCar : Car
{
    public int FuelTank { get; set; }
}

Motorcycle models

public abstract class Motorcycle : Product
{
    public string RiderName { get; set; }
    public bool IsRacing { get; set; }
}

[Table("CrossMotorcycles")]
public class CrossMotorcycle : Motorcycle
{
    public int MaximumJump { get; set; }
}

[Table("KipsMotorcycles")]
public class KipsMotorcycle : Motorcycle
{
    public long MaximumSpeed { get; set; }
}

But the problem is that after creating the tables only the last step of the TPT design follows, and the layer above the TPH design is created.

My code output is the following tables: enter image description here

How should I modify the code to follow the TPT design at all levels of the tables? In the final output I need to make the tables as follows:

enter image description here


Solution

  • I finally got the answer!

    In this case, I needed to make the Car Model and Motorcycle Model unique fields in separate tables, But the above code is made by default with TPH design.

    So we have to change the code this way:

    Base model

    public abstract class Product
    {
        public int Id { get; set; }
        public DateTime ProductionDate { get; set; }
    }
    

    Car models

    [Table("Cars")]
    public abstract class Car : Product
    {
        public string ChassisNumber { get; set; }
        public string DriverName { get; set; }
    }
    
    [Table("TeslaCars")]
    public class TeslaCar : Car
    {
        public string Battery { get; set; }
        public int Temperature { get; set; }
    }
    
    [Table("PorscheCars")]
    public class PorscheCar : Car
    {
        public int FuelTank { get; set; }
    }
    

    Motorcycle models

    [Table("Motorcycles")]
    public abstract class Motorcycle : Product
    {
        public string RiderName { get; set; }
        public bool IsRacing { get; set; }
    }
    
    [Table("CrossMotorcycles")]
    public class CrossMotorcycle : Motorcycle
    {
        public int MaximumJump { get; set; }
    }
    
    [Table("KipsMotorcycles")]
    public class KipsMotorcycle : Motorcycle
    {
        public long MaximumSpeed { get; set; }
    }