0

I have a TPC hierarchy like this:

    public abstract class Base
{
    public Guid BaseId { get; set; }
    public string BaseName { get; set; }
}
public class Sub1 : Base
{
    public Sub2 Vender { get; set; }
}
public class Sub2 : Base
{
    public Sub1 Customer { get; set; }
}
public class MyDbContext : DbContext
{
    public MyDbContext()
        : base("name=db")
    { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Sub1>().HasRequired(x => x.Vender).WithOptional(x => x.Customer);
        modelBuilder.Entity<Sub1>().Map(x =>
            {
                x.ToTable("Sub1s");
                x.MapInheritedProperties();
            }).HasKey(x => x.BaseId);
        modelBuilder.Entity<Sub2>().Map(x =>
            {
                x.ToTable("Sub2s");
                x.MapInheritedProperties();
            }).HasKey(x => x.BaseId);
    }

    public DbSet<Base> People { get; set; }
    public DbSet<Sub2> Venders { get; set; }
    public DbSet<Sub1> Customers { get; set; }
}

Then I run the code and EF create tables (Sub1s and Sub2s). But EF create an aditional Foreign Key for table Sub1, it do not use the Key of Sub1 as the Foreign Key..It generates an additional FK named Vender_BaseId..

Lcng
  • 706
  • 1
  • 8
  • 17
  • This is not the way to model inheritance. `Customer` and `Vendor` should inherit from the base class + for each of them you have to tell EF that `BaseId` is the primary key – Gert Arnold Jun 10 '13 at 08:44
  • Hi Gert Arnold. I use `.HasKey(x => x.BaseId)` to tell EF that `BaseId` is the PK of each subclass. But it does not work. EF still generates the FK Vender_BaseId.. – Lcng Jun 17 '13 at 01:23

0 Answers0