3个外键到一个表到一列

时间:2018-07-02 15:05:22

标签: c# sql .net sql-server entity-framework

有2个实体:“ A”和“ B”。 enter image description here 本质上,“ A”包含以下字段:

 - A_id (PK)
 - B1_id (FK)
 - B2_id (FK)
 - B3_id (FK)

实质上,“ B”:B_id和其他字段。是否可以一对一地建立与EF和MS的关系,其中“ B1_id”,“ B2_id”和“ B3_id”是表“ B”中一个属性B_id的外部键。如果可以的话,如何在类“ A”中命名导航属性,我认为应该有三个?

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

 public class A
    {
        public int Id { get; set; }

        public int B1Id { get; set; }
        public int B2Id { get; set; }
        public int B3Id { get; set; }

        [ForeignKey("B1Id")]
        public B B1 { get; set; }

        [ForeignKey("B2Id")]
        public B B2 { get; set; }

        [ForeignKey("B3Id")]
        public B B3 { get; set; }
    }

    public class B
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

答案 1 :(得分:0)

public class A
{
    public int Id { get; set; }
    //another properties

    public virtual B B1 { get; set; }
    public int B1Id { get; set; }

    public virtual B B2 { get; set; }
    public int B2Id { get; set; }

    public virtual B B3 { get; set; }
    public int B3Id { get; set; }
}

public class B
{
    public int Id { get; set; }
    //another properties

    [InverseProperty(B1)]
    public virtual ICollection<A> A1 { get; set; }
    [InverseProperty(B2)]
    public virtual ICollection<A> A2 { get; set; }
    [InverseProperty(B3)]
    public virtual ICollection<A> A3 { get; set; }
}