In this multi parts series I'll explore how to build inheritance with Entity Framework showing 2 different approaches of inheritance in Entity Framework. Beside that I'll show how to build simple association between 2 entities and show how to provide custom code to retrieve other parts of the relation when inheritance is applied.
My plan not to exceed 3 parts as the subject is not that huge, it is just the demonstration with screen shots that will make the post large that is why I divided it to multi part. I am not good at screen casts beside I don't have a software license to produce one.
Inheritance Types in Entity Framework:
There are 2 models of Inheritance in Entity Framework and they both actually depends on the database design:
- Table-per-Hierarchy Inheritance: One table in storage to maintain data for all the types in an inheritance hierarchy. So basically you have one table in database, but different types in your Entity Model that inherits from a base class and all mapped to that table. This post will focus on this type of Inheritance.
- Table-per-Type Inheritance: Separate table in storage to maintain data for each type in the inheritance hierarchy. That means you might have several tables with one-to-one relationships. Each table is mapped to single Entity in the model. But there is a base Entity that is mapped to the very base table. This is going to be the subject of my next part of this short series. Till then you can watch this video about it.
About the Sample:
The sample I am going to demonstrate here with screen shots is taken from MSDN sample in the links specified above. I found them much clear and easy to demonstrate beside I wasn't able to come out with much simpler sample idea.
How to define a model with Table-per-Hierarchy Inheritance:
At the beginning I'll explore the database design for this subject, and explain why Table-per-Hierarchy must be used to model the inheritance:
This is the only table in hierarchy, but in fact this table store data about different types of persons such as Students, Instructors and Administrators. Those different types of persons are identified by PersonCategory field. Also not all fields are mandatory for each type. For example Students should have EnrollmentDate specified while Instructors should specify their HireDate.
From here we came up with 3 different Entities sharing single table (Table-per-Hierarchy). These Entities are:
- Student: PersonCategory = 1
- Instructor: PersonCategory = 2
- Administrator: PersonCategory = 3
And they are all Person. The existing sample consider a Person itself an instantiatable entity, but for demonstration proposes here Person is just considered an Abstract Entity. Which means a Person must be one of the 3 Entities specified above.
So now the idea is clear why do someone should apply Table-per-Hierarchy inheritance in Entity Framework.
Creating Entity Data Model Wizard:
I'll walk-through the process of creating the Entity Data Model based on the sample database. I'm assuming that you are working on an existing project so I'll skip the project creation step. Screen shots will demonstrate the steps as the following:
- Right Click on the project then Add -> New Item.
- From Add New Item dialog window select ADO.NET Entity Data Model from Template items. Rename to School.edmx or to any other name you like. Click Add
- On Entity Data Model Wizard dialog window make sure that Generate from database is selected. Click Next.
- On next screen, define a new connection to your database or select an existing one. Keep the default settings. Click Next.
- From the next screen, make sure that you select Person table and only that table. Click Finish.

When you are done this should be the simple diagram you'll get:
Creating Sub Entities:
In the following I'll show how to create Entities and make them inherit from Person Entity show above. To create new Entity and make it inherit from Person Entity follow these steps:
- Right Click on the model diagram. From the context menu select Add -> Entity.
- On Add Entity dialog window, set Entity name to Student. Set Base type to Person, this should define the inheritance. Note that once you define Base type, all other properties on the dialog will be disabled. Click Ok.
- Delete EnrollmentDate property on Person Entity as it will be specific Student Entity. Do the same for HireDate as it will be specific for Instructor Entity and AdminDate which will be specific for Administrator Entity.
- Right Click on Student Entity. Select Add -> Scalar Property. Name the property EnrollmentDate. Set its data type on the property window to DateTime.
Repeat the above steps to create the other 2 entities, Administrator and Instructor. Once you finish your model should be similar to this one:
Define Mappings:
It is time to define mapping and show exactly how you are going to differentiate between Entities using Entity Data Model Mapping. Earlier I specified that PersonCategory is used to identify each Entity. For example one PersonCategory is 1 then that means that this is a Student.
To define mapping for each Entity follow these steps for each one -having Student Entity as Example-:
- Right Click on Student Entity and select Table Mapping. This should display Mapping Details Pan for Student Entity.
- From Mapping Details pan under Tables click on <Add a Table or View> and select Person.
- Click on <Add a Condition> and select PersonCategory. Leave the Operator as "=" and set the Value/Property to 1.
- Under Column Mappings make sure that EnrollmentDate column is mapped to EnrollmentDate property.
Repeat the above steps for both Administrator and Instructor Entities and set the mapping condition to their proper values.
Once you are done It is mandatory to delete the PersonCategory property from Person Entity as it is not needed anymore.
Define An Abstract Class:
As I mentioned earlier, for demonstration I need to set Person Entity as Abstract. However you can still define a mapping for it instead of making it abstract. You should set an Base Entity as Abstract only if you know there will be no direct instantiation from that Entity. For the case here, I plan to have nothing but Student, Instructor and Administrator. There is no simple Person.
To set an Entity as Abstract:
- Right Click on the Person Entity, select Properties form context menu.
- From Properties window and Under Code Generation group, set Abstract property to True. Click Ok on the confirmation message that appears.
Conclusion:
Your database design is the primary factor to select between 2 different inheritance models in Entity Framework. In this post I explored the first model Table-per-Hierarchy Inheritance, where only one table is used for all entity type. Many things were running under the hood to generate the CSDL, SSDL and the mapping between both. This XML generated code can be viewed from the ".edmx" file and for more details return to links specified which is pointing to MSDN How-to walk-through. Database script is available with the sample as well as on the original MSND article. On the next part I'll explore hot to implement Table-per-Type Inheritance extending the sample provided in this post.
Download Sample Project.
In this part I'll go through Table-per-Type Inheritance model. There is a video demonstrating this model if you wish to watch. Here I'll update my previous sample with new entities that demonstrate the Table-per-Type Inheritance model. For the differences between 2 models and definitions return to 1st part. The updated sample can be downloaded from here.
How to define a model with Table-per-Type Inheritance:
At the beginning I'll explore the database design for this subject, and explain why Table-per-Type must be used to model the inheritance:
As you notice in the Database diagram. It is typically one-to-one relationships between Department table and other tables. Each department holds its own data on its own table. For example Engineering Department saves its specific data on DeptEngineering table, and at the same time the common data about the department such as Department Name and Administrator are stored in Department table. We are talking about inheritance here, aren't you able to visualize that?!
So from the above Schema, Table-per-Hierarchy Inheritance model will not fit, as every table must have its one separate entity. And here Table-per-Type Inheritance model can exactly fit.
So the Diagram contains 4 tables, each table will represent a separate entity. But Department table/entity will be considered the Base Type for all other 3 entities. And of course it is an Abstract Entity as it is not possible to have a Department with no specialities.
Updating and Refreshing existing Data Model:
As I'm going to update the previous sample, I'll use Visual Studio.Net 2008 SP1 to update the data model and add the new desired entities. To update your model from the database follow these steps:
- Right Click on the model canvas and select Update Model from Database from the context menu.
- From Update Wizard dialog window and under Add tab expand Tables node and select (check) Department, DeptBusiness, DeptEngineering and DeptMusic tables. Click Finish.

This is how the model will look like after update.
Apply Inheritance:
As you noticed there is an association created between Department and Person entities. This is out of our scope right now, so just ignore it.
By default EF didn't recognize the I wish to apply Inheritance, so It will require me to do some modifications to apply inheritance. Also EF generates associations between the newly added entities as you can see in the diagram. As long as we are going to apply Inheritance, associations between Department tables are no longer valid. To apply inheritance follow the following steps:
- Delete Associations between Department tables this should include Department/DeptEngineering, Department/DeptBusiness and Department/DeptMusic.
- Right Click on Department Entity and select Add -> Inheritance from the context menu.
- From Add Inheritance dialog window, confirm that the base entity is Department. Then select DeptBusiness as derived entity.
- Repeat step 3 to select DeptEngineering and DeptMusic as the derived entity.
After you finish the diagram should be closer to this
Define Mappings:
It is much simpler here -in my opinion-. Before we just start mapping and define which exactly will need mapping, you'll notice that the Keys in DeptXxx tables had been removed after defining inheritance. Yes that make sense in fact; because the main Key is in the base entity Department which is DepartmentID. And Now I have some unused properties now which are BusinessDeptID in DeptBusiness Entitiy, EngineeringDeptID in DeptEngineering Entity and DeptMusicID in DeptMusic Entity.
- Delete the following properties
- BusinessDeptID in DeptBusiness Entity.
- EngineeringDeptID in DeptEngineering Entity.
- DeptMusicID in DeptMusic Entity.
- Right Click on DeptBusiness Entity and select Table Mapping from the context menu.
- On the Mapping Details pane and under Column Mappings. For BusinessDeptID Column select DepartmentID Property as mapping property.
- Repeat steps 2-3 to define mapping for EngineeringDeptID Column on DeptEngineering Table and DeptMusicID Column on DeptMusic Table.
Define An Abstract Class:
To set an Department Entity as Abstract:
- Right Click on the Department Entity, select Properties form context menu.
- From Properties window and Under Code Generation group, set Abstract property to True. Click Ok on the confirmation message that appears.
Conclusion:
Again, it is clearly that the database schema is the key choice between using Table-per-Hierarchy Inheritance or Table-per-Type Inheritance. In my opinion, one-to-one relationships give more abstraction and normalization to the database. So unnecessary fields are not exist in the base table. However I would go with Table-per-Hierarchy model for small projects and simple schemas where one table would hold max of 3 to 4 different types. This is my own opinion and it is not following a best practice or not even considered one.
You can download the updated sample here.
I explored how to apply 2 different inheritance models (TPH & TPT) in Entity Framework. In this part I'm going to demonstrate associations between 2 base entities. And how to filter end properties to return specific type (sub entity). Download the sample.
Review Association Ends:
In previous part when I added department tables to the entity model diagram, an associations between Person and Department entities was automatically defined. This relation actually demonstrate the relation between Administrator and Department. It is one-to-many relationship where one person can be administrator of one or many departments.
A collection of Departments is created on Person table and therefor it is inherited on all sub entities! But this make no sense, as a student or instructor has nothing to do with this collection. Beside on the other end at Department a property of type Person is created -I renamed it to Administrator-, while this shouldn't be just any Person, this Person must be of type Administrator.
A few modification should take place in here. The existing association should be deleted and the association ends should be define between Administrator Entity and Department Entity. To do that follow the following steps:
- Delete the current Association between Person and Department.
- Right Click on Administrator Entity, select Add -> Association.
- On Add Association dialog window, optionally you can rename Association Name to "FK_Department_Administrator".
- Confirm that the following information on End at the left hand side:
Entity is Administrator, and Multiplicity is 0..1 (Zero or One) -this is actually because Administrator field in Department table allows Null-. You'll rename the Navigation Property on step 6. - On the other End (right hand side), select Department for Entity, and leave the Multiplicity as it is * (Many). Do not change the Navigation Property name at this End.
- Rename the Navigation Property under the left hand side End to Departments.
- Click Ok.
This is the diagram after applying the above modifications.
Define Association Mapping:
I have to define mapping for the association ends. Will do that using Mapping pane:
- Right Click on the Association between Administrator and Department and select Table Mapping from the context menu.
- On Mapping Details pane, under Association select the foreign key entity which is Department.
- Confirm that Department.DepartmentID is mapped to DepartmentID Column. And for Administrator.PersonID property select Administrator column.

Note: I noticed an issue after applying the above steps. When you validate the diagram immediately after completing the above you'll get an error from EF. For some reason when I change the multiplicity from 0..1 (Zero or One) to 1 (One) and then change it back to 0..1 (Zero or One) the issue disappears. I did that using property window of the Association.
Build Specific Department Query:
As you can see, Departments collection returns all departments of all types. What if you want to return a specific type of departments such as only engineering ones? I raised this question on EF Forums and EF team really responded to that very quickly. To achieve this goal you would add additional properties to the Administrator Entity Class -using another cs file and partial class- Below is the the code that help you achieve this:
1. public IQueryable<DeptBusiness> BusinessDepartments
2. {
3. get
4. {
5. return this.Departments.CreateSourceQuery().OfType<DeptBusiness>();
6. }
7. }
public IQueryable<DeptBusiness> BusinessDepartments
{
get
{
return this.Departments.CreateSourceQuery().OfType<DeptBusiness>();
}
}
It is that simple. And this will generate a specific SQL query to return only Instances of DeptBusiness from DeptBusiness table of course joined with Department base table.
You can read more about CreateSourceQuery Method and OfType<T> method on MSDN. But the following was taken from the remarks about CreateSourceQuery method documentation:
"This property is used to obtain a new instance of ObjectQuery<T> that returns the same set of objects. This is useful as the starting point for a more complex join, union, or filtered query".
And OfType<T> remarks says:
"OfType<TResultType) is used to filter query results by a specific entity or complex type. This supports an Entity Data Model (EDM) with object inheritance"
Conclusion:
There are lots of things to walk through and discover about Entity Framework. In those 3 parts I explored 2 important subjects about Inheritance and Associations. Feel free to leave an comment and share your ideas and experience regarding Entity Framework.
I have an idea of doing a repost to my custom paging using LINQ, but this time using LINQ to Entities.
Click here to download the sample project.
Posted
2009/6/16 1:18
by
革命