Database Reference
In-Depth Information
How It Works
In table per hierarchy inheritance, often abbreviated TPH, a single table is used to represent the entire inheritance
hierarchy. Unlike table per type inheritance, the TPH rows for the derived types as well as the base type are
intermingled in the same table. The rows are distinguished by a discriminator column. In our example,
the discriminator column is EmployeeType.
In TPH, mapping conditions, which are set in entity configuration, are used to indicate the values of the
discriminator column that cause the table to be mapped to the different derived types. We marked the base type as
abstract. By marking it as abstract, we didn't have to provide a condition for the mapping because an abstract entity
can't be created. We will never have an instance of an Employee entity. We did not implement an EmployeeType
property in the Employee entity. A column used in a condition is not, in general, mapped to a property.
The code in Listing 2-25 demonstrates inserting into and retrieving from our model.
Listing 2-25. Inserting into and Retrieving from Our TPH Model
using (var context = new EF6RecipesContext())
{
var fte = new FullTimeEmployee { FirstName = "Jane", LastName = "Doe",
Salary = 71500M};
context.Employees.Add(fte);
fte = new FullTimeEmployee { FirstName = "John", LastName = "Smith",
Salary = 62500M };
context.Employees.Add(fte);
var hourly = new HourlyEmployee { FirstName = "Tom", LastName = "Jones",
Wage = 8.75M };
context.Employees.Add(hourly);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
Console.WriteLine("--- All Employees ---");
foreach (var emp in context.Employees)
{
bool fullTime = emp is HourlyEmployee ? false : true;
Console.WriteLine("{0} {1} ({2})", emp.FirstName, emp.LastName,
fullTime ? "Full Time" : "Hourly");
}
Console.WriteLine("--- Full Time ---");
foreach (var fte in context.Employees.OfType<FullTimeEmployee>())
{
Console.WriteLine("{0} {1}", fte.FirstName, fte.LastName);
}
Console.WriteLine("--- Hourly ---");
foreach (var hourly in context.Employees.OfType<HourlyEmployee>())
{
Console.WriteLine("{0} {1}", hourly.FirstName, hourly.LastName);
}
}
 
Search WWH ::




Custom Search