Database Reference
In-Depth Information
// Map child entities to the 'Discriminator' column, MediaType, from parent table,
// which will determine the type of medium
modelBuilder.Entity<Media>().Map<Article>(x => x.Requires("MediaType").HasValue(1));
modelBuilder.Entity<Media>().Map<Picture>(x => x.Requires("MediaType").HasValue(2));
modelBuilder.Entity<Media>().Map<Video>(x => x.Requires("MediaType").HasValue(3));
base.OnModelCreating(modelBuilder);
}
}
With the Code-First artifacts created, we'll query the model for all of the media and sort the results by the derived
types: Article, Video, and Picture. To do this, follow the pattern in Listing 3-25.
Listing 3-25. Sorting Table per Hierarchy Inheritance by Type
using (var context = new EFRecipesEntities())
{
context.Media.Add(new Article {
Title = "Woodworkers' Favorite Tools" });
context.Media.Add(new Article {
Title = "Building a Cigar Chair" });
context.Media.Add(new Video {
Title = "Upholstering the Cigar Chair" });
context.Media.Add(new Video {
Title = "Applying Finish to the Cigar Chair" });
context.Media.Add(new Picture {
Title = "Photos of My Cigar Chair" });
context.Media.Add(new Video {
Title = "Tour of My Woodworking Shop" });
context.SaveChanges();
}
using (var context = new EFRecipesEntities())
{
var allMedia = from m in context.Media
let mediatype = m is Article ? 1 :
m is Video ? 2 : 3
orderby mediatype
select m;
Console.WriteLine("All Media sorted by type...");
foreach (var media in allMedia)
{
Console.WriteLine("Title: {0} [{1}]", media.Title, media.GetType().Name);
}
}
 
Search WWH ::




Custom Search