Relationship between the tables in Code First Entity Framework



  • There's a glas:

     public class Match
    {
        [DataMember]
        public Guid Id { get; set; }
        [DataMember]
        public virtual Tour Tour { get; set; }
    
    [DataMember]
    public DateTime DateMatch { get; set; }
    
    [DataMember]
    public virtual Team Home { get; set; }
    [DataMember]
    public virtual Team Guest { get; set; }
    
    [DataMember]
    public virtual Result Result { get; set; }
    

    }

    Where? Team Homeand Team Guest other classes that already exist in the database,
    Appendix:

    Violation of PRIMARY KEY constraint 'PK_dbo.Teams'. Cannot insert duplicate key in object 'dbo.Teams'. The duplicate key value is (06f67648-f904-4a4e-8ceb-33c204d8267c). The statement has been terminated.

    How do you not add a new team, but a connection to the existing one?



  • Here's an example of how two can be done. ForeignKey add

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

    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2