Database Reference
In-Depth Information
Listing 6-24. Overriding OnModelCreating in Our DbContext Subclass to Configure TPH Discriminator Values
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Employee>()
.HasKey(e => e.EmployeeId)
.Property(e => e.EmployeeId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Employee>()
.Map<HourlyEmployee>(m => m.Requires("EmployeeType").HasValue("hourly"))
.Map<SalariedEmployee>(m => m.Requires("EmployeeType").HasValue("salaried"))
.Map<CommissionedEmployee>(m => m.Requires("EmployeeType").HasValue("commissioned"))
.ToTable("Employee", "Chapter6");
}
How It Works
Table per Hierarchy inheritance is a flexible modeling technique. The depth and breadth of the inheritance tree can
be reasonably large and is easily implemented. This approach is efficient because no additional tables and their
required joins are involved.
Implementing TPH with a Code-First approach is straightforward because object-oriented inheritance is
hierarchical in nature.
Listing 6-25 demonstrates inserting into and retrieving from our model.
Listing 6-25. Inserting and Retrieving Derived Entities from Employee
using (var context = new EF6RecipesContext())
{
var hourly = new HourlyEmployee { Name = "Will Smith", Hours = 39,
Rate = 7.75M };
var salaried = new SalariedEmployee { Name = "JoAnn Woodland",
Salary = 65400M };
var commissioned = new CommissionedEmployee { Name = "Joel Clark",
Salary = 32500M, Commission = 20M };
context.Employees.Add(hourly);
context.Employees.Add(salaried);
context.Employees.Add(commissioned);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
Console.WriteLine("All Employees");
Console.WriteLine("=============");
foreach (var emp in context.Employees)
 
Search WWH ::




Custom Search