Inheritance with Entity Framework (Code First)


Inheritance with Entity Framework (Code First)

Inheritance makes it possible to create complex models that better reflect developers' thoughts and reduce the work required to interact with those models. Inheritance used with entities serves the same purpose as inheritance used with classes, so developers already know the basics of how this feature works.

Types of Inheritance in Entity Framework

Entity Framework supports three types of inheritances as given below:

  1. Table-per-Hierarchy (TPH)

    The TPH inheritance states that all entities in a hierarchy of entities are mapped to a single table in the storage schema. It means there is only one table in the database, and different Entity types in the Entity model that inherits from a base Entity are mapped to that table. This approach suggests one table for the entire class inheritance hierarchy, and the table includes a discriminator column that distinguishes between inheritance classes. This is a default inheritance mapping strategy in Entity Framework.

  2. Table-per-Concrete-Type (TPC)

    The TPC inheritance states that each concrete class (a class that can be instantiated) in the hierarchy of entities is mapped to a separate table in the storage schema. There is a different table in the database to maintain data for each derived entity type. This approach suggests one table for one concrete class but not for the abstract class. So, if you inherit the abstract class in multiple concrete classes, then the properties of the abstract class will be part of each table of the concrete class.

  3. Table-per-Type (TPT)

    The TPT inheritance states that each entity in the hierarchy of entities is mapped to a separate table in the storage schema. There is a different table in the database to maintain data for each Entity Type, and this approach suggests a separate table for each domain class.

3