2016-04-25 85 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'属性。 –

相关问题