Entity Framework DB-First, implement inheritance

One possible way is to use one table for each type called TPT (table-per-type), which I prefer to use. To achieve this, you define your tables like the model shown in the following picture:

table hierarchy

Note that the relationships between child and base entity are one-to-one on their pk columns, and all common fields are moved to the base table. After creating your tables, right click on the models page in your visual studio, and select Update Model from Database…, and then in the add tab, select these 3 tables to add. At first you should see this model diagram, which needs to be changed a bit:

tables added at first

Do these steps for Person and Organization separately:

  • Right click on entity and select Properties
  • In the Base Type property select Identity
  • Select and then delete the association between this entity and Identity
  • Select and then Delete the PK (ID column) of this entity (Inherits from base entity)

After these steps save your model. Now your model should look like this:

the changed model

Now compile your project and enjoy your life!

Additional resources:
Entity Framework Designer TPH Inheritance

Leave a Comment