2
public abstract class Base {
    public Guid Id {get; set;}
    public Related1 Related1 {get; set;}
    public Related2 Related2 { get; set; }
}

public class Concrete1: Base { }
public class Concrete2: Base { }

public class Related1 {
    public Concrete1 Concrete1 {get; set;}
    public ICollection<Concrete2> Concrete2s {get; set;}
}

public class Related2 {
    public ICollection<Concrete1> Concrete1s {get; set;}
    public ICollection<Concrete2> Concrete2s {get; set;}
}

//OnModelCreating
builder.Entity<Base>()
       .HasDiscriminator<byte>("type")
       .HasValue<Concrete1>(0)
       .HasValue<Concrete2>(1);

builder.Entity<Concrete1>()
       .HasOne(du => du.Related1)
       .WithOne(d => d.Concrete1)
       .HasForeignKey<Concrete1>(du => du.Related1Id);

 builder.Entity<Concrete1>()
        .HasOne(du => du.Related2)
        .WithMany(u => u.Concrete1s)
        .HasForeignKey(eu => eu.Related2Id);

builder.Entity<Concrete2>()
       .HasOne(du => du.Related1)
       .WithMany(d => d.Concrete2s)
       .HasForeignKey(du => du.Related1Id);

builder.Entity<Concrete2>()
       .HasOne(du => du.Related2)
       .WithMany(u => u.Concrete2)
       .HasForeignKey(eu => eu.Related2Id);

//...
public DbSet<Base> Bases { get; set; }
public DbSet<Concrete1> Concrete1s { get; set; }
public DbSet<Concrete2> Concrete2s { get; set; }

I've got error:

The navigation property 'Concrete1' cannot be added to the entity type 'Related1' because its CLR type 'Concrete1' does not match the expected CLR type 'Base'

How can it can be fixed? I have called HasDiscriminator() method, why does EF need Base CLR type as nav in Related1(2), not Concrete1(2)?

Ilya Loskutov
  • 1,967
  • 2
  • 20
  • 34
  • Have you tried declare the navigation property as virtual ? – H. Herzl Jun 29 '17 at 03:01
  • @H. Herzl can it help really? there is EF Core – Ilya Loskutov Jun 29 '17 at 09:33
  • Please add `Related1Id` and `Related2Id` to your code. – grek40 Jun 29 '17 at 12:09
  • How about `builder.Entity().Ignore(x => x.Related1)` and `builder.Entity().Ignore(x => x.Related2)`. I suspect your model is creating some surprise extra relations with an additional foreign keys because the navigation properties in Base are not sufficiently linked to key properties on the same level. – grek40 Jun 29 '17 at 12:21
  • @grek40 I have implemented Ignore() on Base and have got the another error :) https://stackoverflow.com/questions/44824437/ef-core-inherited-entities-has-navs-to-same-table – Ilya Loskutov Jun 29 '17 at 12:34

0 Answers0