entity-frameworkef-code-firsttable-per-type

How to implement inheritance Table-Per-Type in Entity Framework 4.3 via Code First approach?


I have this class hierarchy in code:

[Table("A")]
public class A : IIdentification
{
    public int id { get; set; }
}

[Table("B")]
public class B : A
{
    //some properties here
    public Aid { get; set;}
    ForeignKey("Aid");
    public A A { get; set; }
}

[Table("C")]
public class C : B
{
    //some properties here 
    public Bid { get; set; }
    ForeignKey("Bid");
    public B B { get; set; }
}

[Table("D")]
public class D : C
{
    public Cid { get; set;}
    ForeignKey("Cid");
    public C C { get; set; }
}

How can I make one table with a foreign key for each class or any other possible correct way? Maybe someone could post some sample how to achieve it?

Maybe this is trivial question but I've spent whole day, implemented many solutions described in topics and it still not work. So I'll be very grateful if someone could help me with that.


Solution

  • In mapped inheritance you don't have accessible navigation property to parent entity unless you want to model another relation. Inheritance is "is a" relation so B is A while FK is "has a" relation.

    Here you have a great walkthrough for TPT inheritance.