O'Reilly logo

Programming Entity Framework: Code First by Rowan Miller, Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mapping Inheritance Hierarchies

Entity Framework supports a variety of inheritance hierarchies in the model. Whether you define your model with Code First, Model First, or Database First has no bearing on the types of inheritance or how Entity Framework works with these types for querying, change tracking, and updating data.

Note

Chapter 14 of Programming Entity Framework addresses inheritance in detail. In the following sections, we’ll focus on how to achieve the desired inheritance in your model, but we won’t spend a lot of time on interacting with the types in the hierarchy.

Working with Code First’s Default Inheritance: Table Per Hierarchy (TPH)

Table Per Hierarchy (TPH) describes mapping inherited types to a single database table that uses a discriminator column to differentiate one subtype from another. When you create inheritance in your model, this is how Code First convention will infer the table mapping by default. To see this in action, let’s make two changes to the model. First, we’ll remove the IsResort property from Lodging and then create a separate Resort class that inherits from Lodging. Example 5-16 displays these classes.

Example 5-16. Modified Lodging class and a new Resort class that derives from Lodging

public class Lodging
{
  public int LodgingId { get; set; }

  [Required]
  [MaxLength(200)]
  [MinLength(10)]
  public string Name { get; set; }
  public string Owner { get; set; }
  // public bool IsResort { get; set; }
  public decimal MilesFromNearestAirport { get; set; }
  [InverseProperty ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required