2016-04-25 87 views
1

下面是兩個類的簡單表示。如何在實體框架6代碼優先的同一表之間創建一對一的關係?

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); 

回答

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(); 
      } 
     } 
    } 
+0

然後一個人的對象將有友誼的兩個集合?有沒有其他方式可以讓我們通過一個列表訪問一個人的所有友誼? – ozgur

+0

是的,看看'FShip'屬性。 –

相關問題