Entity Framework Code First - two Foreign Keys from same table

后端 未结 6 1926
别那么骄傲
别那么骄傲 2020-11-22 03:40

I\'ve just started using EF code first, so I\'m a total beginner in this topic.

I wanted to create relations between Teams and Matches:

1 match = 2 teams (ho

6条回答
  •  萌比男神i
    2020-11-22 04:07

    You can try this too:

    public class Match
    {
        [Key]
        public int MatchId { get; set; }
    
        [ForeignKey("HomeTeam"), Column(Order = 0)]
        public int? HomeTeamId { get; set; }
        [ForeignKey("GuestTeam"), Column(Order = 1)]
        public int? GuestTeamId { get; set; }
    
        public float HomePoints { get; set; }
        public float GuestPoints { get; set; }
        public DateTime Date { get; set; }
    
        public virtual Team HomeTeam { get; set; }
        public virtual Team GuestTeam { get; set; }
    }
    

    When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.

    In my case, this simple modification solve the problem.

提交回复
热议问题