Entity Framework code first and Inheritance–Table per hierarchy

Before some day I have posted a blog about Entity Framework code first and Inheritance – Table per type and this post in next in series with that.

In previous post we have learned about how entity framework code first handles inheritance and in this part we are going to extend this and modify some of code of the code of data context to see how its creates a “Table per Hierarchy”.

We’re going to use same code as previous post just going to change EDataContext code like below.

public class EDataContext : DbContext
    public EDataContext() : base("MyConnectionString") 
    public IDbSet<Customer> Customers { get; set; }
    public IDbSet<Employee> Employees { get; set; }
    public IDbSet<Person> Persons { get; set; }

If you see this code carefully and compare is with previous post. The only difference is persons property. That will force Entity Framework to create a single table for inheritance hierarchy. Now we are going to run this application again and see how it creates table. It will create only one table like this.


You can see it has created a only single table called People. Where it has one extra field called Discriminator which separates particular record by Employee or customer. This type of inheritance is called “Table-Per-Hierarchy”. That’s it. Hope you like it. Stay tuned for more…


Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Creating PDF with ASP.Net MVC and RazorPDF

Solution: gulp is not recognized as internal or external command- Visual Studio