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

Fedor picture Fedor · Mar 5, 2012 · Viewed 10.7k times · Source

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.

Answer

Ladislav Mrnka picture Ladislav Mrnka · Mar 5, 2012

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.