entity-frameworkcode-firsttable-per-type

Entity Framework 4.1 Table-Per-Type Mapping


I am trying to write a project using the code-first approach and I have run into the following problem

    public class BaseType
{
    [Key]
    public int id { get; set; }
    public string description { get; set; }
}
public class Type1 : BaseType
{
    public decimal price { get; set; }

}
public class mycontext : DbContext 
{
    public DbSet<BaseType> basetypes { get; set; }
    public DbSet<Type1> type1 { get; set; }

}

when I run the application and I create an object Type1 and use mycontext.type1.ADD(mytype1object); and I look at the database the table for Type one has the correct field but the parent table "basetypes" also has a price field.

Do I have to ignore the field explicitly?

Any suggestions?


Solution

  • By default code first will use TPH (Table Per Hierarchy) inheritance. What this means is that both of your types are being stored in a single table called 'BaseTypes'. You'll notice that it also includes an extra field called 'Discriminator'. EF will store a value in that field to designate which type that each record is.

    If you would like your types to be in different tables you'd need to setup your context for TPT (Table Per Type). You can decorate your classes with a Data Annotation with the table name, or you could use the model binder. Below is the data annotation way.

    [Table("BaseTypes")]
    public class BaseType
    {
        [Key]
        public int id { get; set; }
        public string description { get; set; }
    }
    
    [Table("Type1s")]
    public class Type1 : BaseType
    {
        public decimal price { get; set; }
    
    }