Entity Framework Code First - two Foreign Keys from same table

后端 未结 6 1852
别那么骄傲
别那么骄傲 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:14

    I know it's a several years old post and you may solve your problem with above solution. However, i just want to suggest using InverseProperty for someone who still need. At least you don't need to change anything in OnModelCreating.

    The below code is un-tested.

    public class Team
    {
        [Key]
        public int TeamId { get; set;} 
        public string Name { get; set; }
    
        [InverseProperty("HomeTeam")]
        public virtual ICollection HomeMatches { get; set; }
    
        [InverseProperty("GuestTeam")]
        public virtual ICollection GuestMatches { get; set; }
    }
    
    
    public class Match
    {
        [Key]
        public int MatchId { 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; }
    }
    

    You can read more about InverseProperty on MSDN: https://msdn.microsoft.com/en-us/data/jj591583?f=255&MSPPError=-2147217396#Relationships

提交回复
热议问题