代码改变世界

Entity Framework Code-First(7):Inheritance Strategy

2016-07-05 16:19  追忆似水流年  阅读(231)  评论(0编辑  收藏  举报

Inheritance Strategy in Code-First:

We have seen in the Code First Conventions section that it creates database tables for each concrete domain class. However, You can design your domain classes using inheritance. Object-oriented techniques include "has a" and "is a" relationship, whereas SQL-based relational model has only a "has a" relationship between tables. SQL database management systems don't support type inheritance. So, how would you map object-oriented domain classes with the relational database?

Below are three different approaches to represent an inheritance hierarchy in Code-First:

  • Table per Hierarchy (TPH): This approach suggests one table for the entire class inheritance hierarchy. Table includes discriminator column which distinguishes between inheritance classes. This is a default inheritance mapping strategy in Entity Framework.
  • Table per Type (TPT): This approach suggests a separate table for each domain class.
  • Table per Concrete class (TPC): 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.

We are not going into detail here. Visit the following reference link for more detailed information:

  1. Inheritance with EF Code First: Table per Hierarchy (TPH)
  2. Inheritance with EF Code First: Table per Type (TPT)
  3. Inheritance with EF Code First: Table per Concrete class (TPC)

We have seen default Code First conventions in the previous section. Learn how to configure domain classes in order to override these conventions in the next section.