Entity Framework Code First - two Foreign Keys from same table

后端 未结 6 1840
别那么骄傲
别那么骄傲 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条回答
  •  北海茫月
    2020-11-22 04:13

    InverseProperty in EF Core makes the solution easy and clean.

    InverseProperty

    So the desired solution would be:

    public class Team
    {
        [Key]
        public int TeamId { get; set;} 
        public string Name { get; set; }
    
        [InverseProperty(nameof(Match.HomeTeam))]
        public ICollection HomeMatches{ get; set; }
    
        [InverseProperty(nameof(Match.GuestTeam))]
        public ICollection AwayMatches{ get; set; }
    }
    
    
    public class Match
    {
        [Key]
        public int MatchId { get; set; }
    
        [ForeignKey(nameof(HomeTeam)), Column(Order = 0)]
        public int HomeTeamId { get; set; }
        [ForeignKey(nameof(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 Team HomeTeam { get; set; }
        public Team GuestTeam { get; set; }
    }
    

提交回复
热议问题