Entity Framework 4.1 Inheritance – Table per Hierarchy

By default if you apply inheritance in Entity Framework 4.1 the model that will be used is table per Hierarchy. Meaning that this object model:Will be translated to this table in your database:

So we get one table containing all the fields from all the classes in the hierarchy and one additional discriminator column which will be filled with the name of the class. Using that value EF knows what class it needs to create an instance from. Create a mapping for this manually would be done by subclassing DbContext and implement OnModelCreating as illustrated in the following piece of code:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        .Map(x => x.ToTable("Products"))
        .Map<Book>(x => x.ToTable("Products"))
        .Map<Cd>(x => x.ToTable("Products"));

One Reply to “Entity Framework 4.1 Inheritance – Table per Hierarchy”

  1. Good article, if a little brief. Especially handy was the OnModelCreating override code. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.