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; }
我有错误:
导航属性&#39; Concrete1&#39;无法添加到实体类型 &#39; Related1&#39;因为它的CLR类型&#39; Concrete1&#39;不符合 预期的CLR类型&#39; Base&#39;
如何解决?我已经调用了HasDiscriminator()方法,为什么EF在Related1(2)中需要Base CLR类型为nav,而不是Concrete1(2)?