EF Core 单列的多重关系

EF Core multiple realationship of a single column

我正在使用 EF Core 3.1,我有五个模型:PlantAreaUnitSchemaEntitiesSchema。 在EnititiesSchema中,EntityId可能是Plant(PlantId)、Area(AreaId)、Unit(UnitId)表的外键。 如何处理这些表之间的这种可选关系?

谢谢

public class EntitiesSchema
{
    public int Id { get; set; }
    public int EntityId { get; set; }
    public int TopicId { get; set; }
    public int SchemaId { get; set; }
    public string Description { get; set; }
    public Schema Schema { get; set; }
    public ICollection<Topic> Topic { get; set; }
}

不,您不能将一个外键关联到多个表。但是你可以把另一个属性命名为EntityType来存储实体的类型。然后在客户端,你可以处理它。 EntityType 可以是枚举类型。

另一种方法是将 "EntitesSchemaId" 存储在 PlantAreaUnit 等模型中,并将它们与 EntitiesSchema 相关联。

您可以创建一个中间实体来映射到不同的实体类型。 :

Public class EntityMap
{
    public int Id {get;set;}
    public string EntityKind {get;set;} // could be "Plant", "Area", "Unit", "Schema"
}

public class Plant 
{
    public int Id {get;set;}
    public string EntityKind {get;set;} = "Plant";
}

public class EntitySchema
{
     public int Id {get;set;}
     public int EntityMapId {get;set;}
     public EntityMap Map {get;set;}
}

从单个模式读取数据的逻辑必须在客户端中实现,但可以在 EntityMap 中添加实体的公共属性。 这是您可能想参考的类似答案: