How to configure inheritance mappings in Entity Framework 7

Table Per Concrete type is new in Entity Framework 7. Using TPC or existing inheritance mapping approaches supported in Entity Framework Core 6 such as Table Per Hierarchy or Table Per Type is super easy.

For example if we have a simple Animal hierarchy like…

… a sample context where I tell Entity Framework to configure this hierarchy using TPH, TPT and TPC is below…

Click the image for a larger view in a new tab…

Entity Framework 7 has introduced three new methods to configure which type of mapping you want…

  1. UseTphMappingStrategy()
  2. UseTptMappingStrategy()
  3. UseTpcMappingStrategy()

As can be seen above, we need to call these on the root entity. TPH is the default so the call to UseTphMappingStrategy() is technically not needed but can be good to include sometimes for explicitness.

Since Identity columns cannot not be used for entity IDs in the Table-per-Concrete type approach we must uses sequences as can be seen above.

The three different database structures which are created for the Animal hierarchy using the different inheritance mapping types are below…

Entity Framework Table Per Hierarchy Inheritance example

Here we can see everything is in one table so a lot of columns are nullable. Modern DBs can handle lots of null columns just fine but consider making the columns sparse to save space.

The TPH approach is the default in Entity Framework Core and is super performant as there is no overhead of joining multiple tables.

Entity Framework Table Per Type Inheritance example

In Table Per Type (TPT) we can see that the abstract class Animal has been given its own table. This is not ideal as it means most queries will require joins to get data.

Entity Framework Table Per Concrete type Inheritance example

This is the new approach in Entity Framework 7 and aims to overcome some of the performance issues with TPT by not creating tables for abstract types such as Animal in this case.

The Table Per Concrete (TPC) is the best performer of all Entity Framework inheritance mapping approaches when we query mostly on a single leaf entity such as cat or dog or farm animal and not all animals for example.

Leave a Reply

Your email address will not be published.