Skip to main content

Using Table-Per-Hierarchy (TPH) Mapping

Introduction to Table-Per-Hierarchy (TPH) Mapping

Table-Per-Hierarchy (TPH) mapping is one of the most popular inheritance mapping strategies in the Entity Framework ORM. It maps an object-oriented class hierarchy to a single table in the database, by using the discriminator column to differentiate between the classes. It is the simplest of the ORM inheritance mapping strategies and offers good performance for most scenarios.

Benefits of TPH Mapping

  • It is the simplest of the ORM inheritance mapping strategies.
  • It offers good performance for most scenarios.
  • It can be used with legacy databases which do not support inheritance.
  • It can handle polymorphic queries with ease.

Drawbacks of TPH Mapping

  • It doesn't support inheritance between tables.
  • It can lead to redundant data if the classes share common properties.
  • It can be difficult to maintain in the long run, as the table structure must be modified to accommodate new classes.

Examples of TPH Mapping

Let's consider a simple example of TPH mapping with the following classes: public abstract class Animal { public int Id { get; set; } public string Name { get; set; } } public class Cat : Animal { public string Color { get; set; } } public class Dog : Animal { public DateTime LastWalk { get; set; } } In order to map these classes to a single table, we need to add a discriminator column to the table. The discriminator column is used to differentiate the different classes in the hierarchy. The table structure would look like this: CREATE TABLE Animals ( Id INT PRIMARY KEY, Name VARCHAR(50), Discriminator VARCHAR(50), Color VARCHAR(50), LastWalk DATETIME ) The Discriminator column will contain the type of the class, such as "Cat" or "Dog". The other columns will contain the properties of the respective classes.

Tips for Using TPH Mapping

  • Always use a discriminator column to differentiate between the classes in the hierarchy.
  • Avoid using TPH mapping if the classes in the hierarchy share common properties, as it can lead to redundant data.
  • Be aware that TPH mapping can be difficult to maintain in the long run, as the table structure must be modified to accommodate new classes.
  • Use TPH mapping with legacy databases which do not support inheritance, as it offers good performance for most scenarios.