Entity Framework Table Per Concrete Type foreign key

836 Views Asked by At

I have the following class hierarchy

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

   public virtual IColection<B> Items {get; set; }
}

public abstract class B
{
   public int Id {get; set; }

   public A Parent {get; set; }
}

public class C : B
{
   public String Name {get; set; }
}

I'm trying to use Table per concrete type hierarchy mapping and the following code to DataContext

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<C>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("C_Table");
        });
    }

Entity Framework still creates two tables. One for class B that includes Id and A_Id field for foreign key. Second one for C with all fields except reference to A.

Is it possible to configure EF not to create table for B? I want to have separate table for each derived class but without common table.

1

There are 1 best solutions below

0
On

In EF core, modelBuilder.Ignore will do the magic:

modelBuilder.Ignore<B>();

Not sure if EF 5-6 has similar function.

BUT: Go through the post Inheritance with EF Code First - Table per Hierarchy (TPH), you will find:

This mapping strategy is a winner in terms of both performance and simplicity. It’s the best-performing way to represent polymorphism—both polymorphic and nonpolymorphic queries perform well—and it’s even easy to implement by hand. Ad-hoc reporting is possible without complex joins or unions. Schema evolution is straightforward.

So, for performance reason, maybe you can consider above approach, but it really depends on your real project. if you have tons of children classes, then split them to tables as you wanted.