@andreabelloni I don't think that EF supports the mapping that you are trying to make. One problem is that the same navigation property, defined on A, is being used for two different relationships: B -> D, and C -> D. You could get the table structure similar to what you want if you are willing to have a single relationship from A to D. This will mean that D has only one collection that will contain both B and C instances. The following code sets up such a mapping:
Thanks,
Arthur
public abstract class A
{
public int ID { get; set; }
public string Code { get; set; }
public int IdExt { get; set; }
public virtual D D { get; set; }
}
public class B : A { }
public class C : A { }
public class D
{
public int ID { get; set; }
public virtual ICollection<A> ASet { get; set; }
}
public class SomeContext : DbContext
{
public DbSet<B> BSet { get; set; }
public DbSet<C> CSet { get; set; }
public DbSet<D> DSet { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder
.Entity<A>()
.ToTable("A");
modelBuilder
.Entity<A>()
.Map<B>(t => t.Requires("Type").HasValue("B").IsRequired())
.Map<C>(t => t.Requires("Type").HasValue("C").IsRequired());
modelBuilder
.Entity<A>()
.HasRequired(t => t.D)
.WithMany(t => t.ASet)
.HasForeignKey(t => t.IdExt);
}
}
This results in an A table that looks like this:- ID: PK
- Code
- IdExt: FK
-
Type: Discriminator
Thanks,
Arthur