Entity Framework Inheritance Table Per Type (TPT) in .NET

Table per Type (TPT) is a type of inheritance mapping in Entity Framework where each derived entity type is mapped to a separate table in the database.

For example, consider the following object model:

Copy codepublic abstract class Vehicle
{
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}

public class Car : Vehicle
{
public int NumberOfDoors { get; set; }
}

public class Truck : Vehicle
{
public int LoadCapacity { get; set; }
}

In this object model, there is a base class called Vehicle and two derived classes called Car and Truck. If you were to use TPT inheritance mapping in Entity Framework, each of these classes would be mapped to a separate table in the database. The Vehicle table would contain columns for the Id, Make, and Model properties, and the Car and Truck tables would each contain a column for the Id property (to create the inheritance relationship) as well as their respective additional properties, NumberOfDoors and LoadCapacity.

To set up TPT inheritance mapping in Entity Framework, you can use the ToTable method in the EntityTypeConfiguration class:

Copy codepublic class VehicleConfiguration : EntityTypeConfiguration<Vehicle>
{
public VehicleConfiguration()
{
ToTable(\"Vehicles\");
}
}

public class CarConfiguration : EntityTypeConfiguration<Car>
{
public CarConfiguration()
{
ToTable(\"Cars\");
}
}

public class TruckConfiguration : EntityTypeConfiguration<Truck>
{
public TruckConfiguration()
{
ToTable(\"Trucks\");
}
}

This example shows how to create separate tables for each of the Vehicle, Car, and Truck classes using TPT inheritance mapping.

Overall, TPT inheritance mapping is a useful way to map an object-oriented inheritance hierarchy to a relational database, allowing you to take advantage of the benefits of both worlds.

To read more about Table Per Type refer to Microsoft documentation.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *