Database Reference
In-Depth Information
This model uses Table per Hierarchy inheritance (TPH), which is a feature of Entity Framework. TPH creates an
inheritance structure where a parent and given number of related child classes all derive from a single database table.
In this example, the Media entity has a property entitled MediaType, which is used as a discriminator property for
our TPH construct. The value of MediaType determines which derived type (Article, Picture, or Video) is represented
by a row from the database. The discriminator column has a value of 1 for an Article type, 2 for a Video type, and 3 for
the Picture type. Because the property is used only to determine the derived type, it is not shown as part of the Media
entity.
To start, this example leverages the Code-First approach for Entity Framework. In Listing 3-23, we create the
entity classes. To keep the example simple, we'll create empty child objects, as we only want to demonstrate how to
order a query based on a derived type.
Listing 3-23. Parent and Child Entity Types
public class Media
{
public int MediaId { get; set; }
public string Title { get; set; }
}
public class Article : Media
{
}
public class Picture : Media
{
}
public class Video : Media
{
}
Next, in Listing 3-24, we create the DbContext object, which is your gateway into Entity Framework functionality
when leveraging the Code-First approach. Note how in the OnModelCreating method, we explicitly map the
discriminator column, MediaType, to the child entities using a FluentAPI coding approach (that is, chaining together
extension methods to create an operation).
Listing 3-24. The DbContext Object
public class EFRecipesEntities : DbContext
{
public EFRecipesEntities()
: base("ConnectionString")
{
}
public DbSet<Media> Media { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Media>().ToTable("Chapter3.Media");
 
Search WWH ::




Custom Search