简体   繁体   中英

Foreign Key with multiple Inherited Classes EF Core 2.0 Code First

I have 2 classes ( A & B ), both inherit from my Base class.
My Side Class has a BaseId and a Base field.

I'm working with Code First and Table per Concrete Class (TPC)

I'm trying to create Foreign keys to connect the Side table with my A & B table. When i create only one relation with fluent api it works fine. But when i add the second one, the new migration drop the FKs from A and create a new one for B . Why i can't create 2 relations?

public class Base
{
    public int    Id   { get; set; }
    public string Name { get; set; }
}

public class A : Base
{
    public string StringA { get; set; }
}

public class B : Base
{
    public string StringA { get; set; }
}

public class Side
{
    public int Id { get; set; }
    public int BaseId { get; set; }
    public Base Base { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Side>().HasOne(s => (A) s.Base);
    modelBuilder.Entity<Side>().HasOne(s => (B) s.Base);
}

Hopefully you already got this figured out, but as previously mentioned table TPC isn't supported! You can use TPH.

To do TPH just do the following:

modelBuilder.Entity<Side>.ToTable("Sides")
            .HasDiscriminator<SideType>("SideType")
            .HasValue<A>(SideType.BASE_A)
            .HasValue<B>(SideType.BASE_A);



 public enum SideType {
    BASE_A = 100,
    BASE_B = 500
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM