Entity Framework Code First Inheritance : Table Per Type and Table Per Hierarchy
Recently i answered a question in stackoverflow about how to create separate tables for each sub type when handling inheritance. Today i thought of expanding it with some sample source code and share it here.
While working with data driven applications, Some times we need to implement Inheritance in our code as well as the data storage. Let's take a look at how Entity Framework CodeFirst handles this
Table Per Hierarchy (TPH)
By default, Entity framework code first uses Table Per Hierarchy method to handle inheritance when creating tables from entities. in TPH, All Data in the hierarchy will be saved in a single database table and it uses a Discriminator column to indentify which record belongs to which sub type. The value of this column will be the name of the subtype.
Le'ts take an example.
I have a base class called Vehicle from where I am inheriting a Car class and a MotorCycle class.
So CodeFirst will create a table like this. All the properties in the inheritance hierarchy is in the same table with the Discriminator field.
If you look at the data ( after adding some via the application), it will be like this. You can see that the value of Discriminator column is the name of the type.
The records with Discriminator value as "Car" are the records for Car type and the records with Discriminator value as "Motorcycle" are for Motorcycle entity. Note the HandleBarColor is null for the first two records because those records are for the Car type and we don't have a property for the Car type in our inheritance hierarchy. So it became NULL.
Table Per Type (TPH)
In Table per Type method, Entity Framework CodeFirst will create a table for the base class ( with the base class properties as the columns) and individual tables for each subtype in the hierarchy. To do this, we can override the OnModelCreating method of DBContext and write some fluent API Code.
As a result, Now our tables will be like this.
And the data will look like this
Note the ID value of the Derived type tables are same as the Identity column value of the base type record.
I hope this gives you some basic idea about how entity framework handles inheritance when doing code first way of development. You can download the sample source code which i used in the post here. Don’t forget to leave me a comment, if this post helps you.