首页 > 解决方案 > Entity Framework Core 中基于条件的外键

问题描述

我必须创建一个基于类之间一对多关系的条件。我有以下课程。

public enum Type
{
    Type1,
    Type2
}
public Class Base1
{
    public int Id {get; set;}
    public string Prop {get; set;}
    public List<NProp> NProps {get; set;}
}
public Class Base2
{
    public int Id {get; set;}
    public string Prop {get; set;}
    public List<NProp> NProps {get; set;}
}
public class NProp
{
    public Type Type {get; set;}
    public int BaseId {get; set;} //Foreign Key
    public string NProp {get; set;}
}

现在,在 NProp 类中,有一个外键baseId应该是Base1if the TypeisType1Base2if the Typeis的外键Type2。首先,这可能吗?如果是,那么如何?

标签: sql-serverentity-framework.net-coreef-code-firstentity-framework-core-2.2

解决方案


不,这是不可能的。您应该使用两个 FK。每个基地一个。


推荐阅读