C# ef核心代码第一个泛型继承映射

C# ef核心代码第一个泛型继承映射,c#,.net-core,domain-driven-design,entity-framework-core-2.1,ef-code-first-mapping,C#,.net Core,Domain Driven Design,Entity Framework Core 2.1,Ef Code First Mapping,所有位置都有一个多对1的位置。 不同的位置类型具有不同的位置类型 型号: public abstract class Location { public int Id { get; set; } public string Name { get; set; } public int AreaId { get; set; } public Area Area { get; set; } public byte[] ConcurrencyToken { get

所有位置都有一个多对1的位置。 不同的位置类型具有不同的位置类型

型号:

public abstract class Location
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int AreaId { get; set; }
    public Area Area { get; set; }
    public byte[] ConcurrencyToken { get; set; }
}
public abstract class Location<T> : Location where T : Position
{
    public ICollection<T> Positions { get; set; } = new List<T>();
}

public class Bay : Location<BayRow> {}
public class StandardLocation : Location<Position> {}

public class Position
{
    public int Id { get; set; }
    public int? Place { get; set; }
    public int LocationId { get; set; }
    public Location Location { get; set; }
    public byte[] ConcurrencyToken { get; set; }
}
public class BayRow : Position
{
    public int? Row { get; set; }
}
上面是缩写,每一个都有更多的实现。所有位置都扩展了泛型类

映射:

modelBuilder.Entity<Position>(entity =>
{                
    entity.ToTable("Position")
          .HasDiscriminator<int>("Type")
          .HasValue<Position>(1)
          .HasValue<BayRow>(2);
    entity.Property(x => x.ConcurrencyToken).IsConcurrencyToken();
    //THIS IS THE ISSUE*
    entity.HasOne(x => x.Location as Location<Position>).WithMany(x => x.Positions).HasForeignKey(x => x.LocationId);
});

modelBuilder.Entity<Location>(entity =>
{
    entity.HasIndex(x => new {x.Name, x.AreaId}).IsUnique(true);
    entity.Property(x => x.ConcurrencyToken).IsConcurrencyToken();
    entity.HasDiscriminator<int>("Type")
          .HasValue<StandardLocation>(1)
          .HasValue<Bay<BayRow>>(2)
});

modelBuilder.Entity<Bay<BayRow>>(entity =>
{
    entity.HasMany(x => x.Positions).WithOne(x => x.Location as Bay<BayRow>)
                .HasForeignKey(x => x.LocationId).OnDelete(DeleteBehavior.Cascade);
});

modelBuilder.Entity<BayRow>(entity =>
{
    entity.Property(x => x.Row).HasColumnName("Row");
});
*非通用位置没有位置

我尝试将集合添加到基本位置纯粹是为了映射,以避免ef复制/混淆每个位置Impl,即BayId作为LocationId

publiic ICollection<Position> Positions { get; set; }
使用新关键字隐藏基本集合,但ef投影2个集合

public new ICollection<T> Positions { get; set; }

如果您有任何见解,我将不胜感激。

如果不生成两个表(一个用于Bay,一个用于StandardLocation),我不确定Entity Framework是否支持此功能

您可以尝试将此作为解决方法

公共接口ITypedPosition,其中T:位置 { IEnumerable Positions{get;} } 公共抽象类位置 { 公共int Id{get;set;} 公共字符串名称{get;set;} 公共int AreaId{get;set;} 公共区域{get;set;} 公共字节[]并发肯{get;set;} 公共ICollection位置{get;set;} } 公共类间隔:位置,ITypedPosition { IEnumerable ITypedPosition.Positions=>base.Positions.OfType; } 公共类标准位置:位置,ITypedPosition { IEnumerable ITypedPosition.Positions=>base.Positions.OfType; }
通过一个小的调整解决了我的用例。谢谢