Entity Framework Code First - two Foreign Keys from same table

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

    Try this:

    public class Team
    {
        public int TeamId { get; set;} 
        public string Name { get; set; }
    
        public virtual ICollection HomeMatches { get; set; }
        public virtual ICollection AwayMatches { get; set; }
    }
    
    public class Match
    {
        public int MatchId { get; set; }
    
        public int HomeTeamId { get; set; }
        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; }
    }
    
    
    public class Context : DbContext
    {
        ...
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity()
                        .HasRequired(m => m.HomeTeam)
                        .WithMany(t => t.HomeMatches)
                        .HasForeignKey(m => m.HomeTeamId)
                        .WillCascadeOnDelete(false);
    
            modelBuilder.Entity()
                        .HasRequired(m => m.GuestTeam)
                        .WithMany(t => t.AwayMatches)
                        .HasForeignKey(m => m.GuestTeamId)
                        .WillCascadeOnDelete(false);
        }
    }
    

    Primary keys are mapped by default convention. Team must have two collection of matches. You can't have single collection referenced by two FKs. Match is mapped without cascading delete because it doesn't work in these self referencing many-to-many.

提交回复
热议问题