How does EF map non-abstract base types when ToTable isn't called?

279 views Asked by At

I am using EF5 Code-first with entity classes like so:

public class Base {
    public int Id { get; set; }
}

public class Derived : Base { // there are other derived types as well
}

and then I configure the derived entity as follows:

var config = new EntityTypeConfiguration<Base>();
config.Map<Derived>(m =>
{
    m.MapInheritedProperties();
    m.ToTable("derived");
});

DbModelBuilder modelBuilder = ...
modelBuilder.Configurations.Add(config);

In my application I then call:

new MyDbContext().Set<Derived>().First();

What is the expected behavior for this call?

Weirdly, I seem to be getting inconsistent behavior for hierarchies configured exactly the same way. Sometimes this fails because it tries to query "dbo.Base" and sometimes it correctly queries "dbo.Derived".

1

There are 1 answers

1
Alexandre Rondeau On

The default value for EF derive type mapping is Table per Hierarchy. You can get all the defaults on that blog

On you base table a new field called "Discriminator" will be added add all fields in the derive type will be created in the database a nullable column.

In your case, this should be TPT, so the table "base" will contain all fields of the base class and the table "derived" will contains all the fields of the derived class. Both table will have a shared primary key.

From the blog: There are three different approaches to representing an inheritance hierarchy:

  • Table per Hierarchy (TPH): Enable polymorphism by denormalizing the SQL schema, and utilize a type discriminator column that holds type information.
  • Table per Type (TPT): Represent "is a" (inheritance) relationships as "has a" (foreign key) relationships.
  • Table per Concrete class (TPC): Discard polymorphism and inheritance relationships completely from the SQL schema.

Each of the tree scenarios have pros and cons it's really well described in Morteza Manavi's blog