如何在Entity Framework 6 Code First中的同一个表之间创建一对一的关系?

时间:2016-04-25 10:49:14

标签: c# entity-framework entity-framework-6 ef-migrations

这是两个类的简单表示。

public class Person
{
    [Key]
    public int ID {get; set;}
    public virtual ICollection<Friendship> FShip{ get; set; }
}

    public class Friendship
    {
        [Key]
        public int ID { get; set; }

        [ForeignKey("Friend1ID")]
        public virtual Person Friend1{ get; set; }
        public int Friend1ID { get; set; }

        [ForeignKey("Friend2ID")]
        public virtual Person Friend2{ get; set; }
        public int Friend2ID{ get; set; }

        public double FriendshipScrore{ get; set; }
    }

创建表格时,我希望每个朋友都有两个外键。但是Person表还有另一个外键。 Person_ID(这是问题)

以下是迁移代码中的相应部分。

ForeignKey("dbo.Persons", t => t.Friend1ID, cascadeDelete: true)
.ForeignKey("dbo.Persons", t => t.Friend2ID, cascadeDelete: true)
.ForeignKey("dbo.Persons", t => t.Person_ID)
.Index(t => t.Friend1ID)
.Index(t => t.Friend2ID)
.Index(t => t.Person_ID);

1 个答案:

答案 0 :(得分:2)

您还应该调整Person类,以明确指定Friend1集的链接和Friend2类设置的Friendship

    public class Person
    {
        [Key]
        public int ID {get; set;}

        [InverseProperty("Friend1")]
        public virtual ICollection<Friendship> FShip1{ get; set; }

        [InverseProperty("Friend2")]
        public virtual ICollection<Friendship> FShip2{ get; set; }

        [NotMapped]
        public List<Friendship> FShip{ get { 
                  return FShip1.Union(FShip2).ToList();
             } 
        }
    }