简体   繁体   中英

How to create one-to-one relationship between same table in Entity Framework 6 Code First?

Here is a simple representation of the two classes.

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

When the table is created I was expecting two foreign keys for each friend. But there is another foreign key for Person table. Person_ID (which is the problem)

Below is the corresponding part in Migration code.

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

You should also tune Person class to specify explicitly links to Friend1 set and Friend2 set at Friendship class:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM