开发者

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 t开发者_Python百科he 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?


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; }

}


I cannot reproduce your problem - in fact if I use the same model with EF 4.1 the DB that's generated only has a BaseTypes table that contains both elements of BaseType and Type1 - the rows with BaseType elements just have a null value as price. So you are not using TPT but TPH currently. To switch to TPT you could annotate your class Type1 or use the fluent API:

[Table("Type1s")]
public class Type1 : BaseType
{
    public decimal price { get; set; }

}


Thanks for the input BrokenGlass and ckal. I was tying to user the "Table(Name)" annotation and fluent API and I followed all of the steps and I kept ending up with a table for both BaseTypes and Type1s and the BaseTypes table contained fields for the fields in Type1s.

However, after I went ahead and made table names for each of the remaining classes in my model, I tried it an everything worked.

I am not sure if this was a fluke, or if I found a bug, but everything is working now.

Thanks again for the quick responses.

Sanity Restored .... For Now!!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜