entity-framework/ef6/modeling/designer/inheritance/tpt.md
This step-by-step walkthrough shows how to implement table-per-type (TPT) inheritance in your model using the Entity Framework Designer (EF Designer). Table-per-type inheritance uses a separate table in the database to maintain data for non-inherited properties and key properties for each type in the inheritance hierarchy.
In this walkthrough we will map the Course (base type), OnlineCourse (derives from Course), and OnsiteCourse (derives from Course) entities to tables with the same names. We'll create a model from the database and then alter the model to implement the TPT inheritance.
You can also start with the Model First and then generate the database from the model. The EF Designer uses the TPT strategy by default and so any inheritance in the model will be mapped to separate tables.
Table-per-Hierarchy (TPH) is another type of inheritance in which one database table is used to maintain data for all of the entity types in an inheritance hierarchy. For information about how to map Table-per-Hierarchy inheritance with the Entity Designer, see EF Designer TPH Inheritance.
Note that, the Table-per-Concrete Type Inheritance (TPC) and mixed inheritance models are supported by the Entity Framework runtime but are not supported by the EF Designer. If you want to use TPC or mixed inheritance, you have two options: use Code First, or manually edit the EDMX file. If you choose to work with the EDMX file, the Mapping Details Window will be put into “safe mode” and you will not be able to use the designer to change the mappings.
To complete this walkthrough, you will need:
The Entity Designer, which provides a design surface for editing your model, is displayed. All the objects that you selected in the Choose Your Database Objects dialog box are added to the model.
We will now delete the CourseID property from OnlineCourse and OnsiteCourse because these classes inherit CourseID from the Course base type.
Open the Program.cs file where the Main method is defined. Paste the following code into the Main function. The code executes three queries. The first query brings back all Courses related to the specified department. The second query uses the OfType method to return OnlineCourses related to the specified department. The third query returns OnsiteCourses.
using (var context = new SchoolEntities())
{
foreach (var department in context.Departments)
{
Console.WriteLine("The {0} department has the following courses:",
department.Name);
Console.WriteLine(" All courses");
foreach (var course in department.Courses )
{
Console.WriteLine(" {0}", course.Title);
}
foreach (var course in department.Courses.
OfType<OnlineCourse>())
{
Console.WriteLine(" Online - {0}", course.Title);
}
foreach (var course in department.Courses.
OfType<OnsiteCourse>())
{
Console.WriteLine(" Onsite - {0}", course.Title);
}
}
}