EF Feature CTP5: Inheritance Scenarios with Code First Fluent API
One of the interesting features of Code First fluent API is the ability to configure inheritance in your model. Since one of the strengths of an O/RM solution is its ability to map inheritance then this feature is a must in every mapping scenario (may it be Model first, Database First or Code First). In this post I’ll show how to configure inheritance by using the fluent API.
Revisiting Entity Framework Inheritance Types
In the past I wrote a series of posts about inheritance mapping in Entity Framework which you can read here:
- Entity Framework Inheritance Types
- Table Per Type Inheritance in Entity Framework
- Table Per Hierarchy Inheritance in Entity Framework
- Table Per Concrete Type Inheritance in Entity Framework
Configure Inheritance Using Code First Fluent API
In the previous CTPs in order to create inheritance we had to use the MapHierarchy method which was very tedious. In this version the MapHierarchy method was replaced by the Map method (and not in all the inheritance mapping scenarios you’ll need to use it). Lets explore the inheritance types:
Table per type (TPT) inheritance
In order to create this type of mapping all you have to do is to use the ToTable method:
You start with creating the inheritance in the model itself (OnLineCourse inherit from Course) and then in the DbContext’s OnModelCreating method you specify that every type will be mapped to its own table using the ToTable method.
Table per hierarchy (TPH) inheritance
In order to create this type of mapping you need to use the Map method. In the lambda the Map method gets you write the discriminator field and its values using the Requires and HasValue methods. In the following example you can see how to do exactly that:
Table per concrete type (TPC) inheritance
In order to create this type of mapping you will start as it is a table per type inheritance configuration. The only change is the use of the Map method on the concrete type. In the method lambda you will use the MapInheritedProperties method to indicate it is a concrete type:
Here is a simple check to see how the database is created in each inheritance type:
Pay attention that in the TPC inheritance the database will be created properly and the insert will succeed but there will be an exception of overlapping keys (both courses will be created with CourseID of 1 and in the context there will be overlapping).
Using the Code First fluent API for inheritance is easy. In the post I showed how you can do that using the three main inheritance scenarios in Entity Framework.