Dennis Mitchell
Dennis Mitchell

Reputation: 17

Entity Framework Self-Referencing Entity

I am building a database to store a double-elimination tournament bracket. Each match in the tournament has two teams who play each other. In the first round of the tournament, the teams are fixed based on seeding. In subsequent rounds the teams are winners and losers of previous matches.

public class Match
{
    public int MatchId { get; set; }
    [Required]
    public virtual Round Round { get; set; }
    // other stuff to keep track of match results
    public virtual Team Team1 { get; set; }
    public virtual Team Team2 { get; set; }       
    [Required]
    public TeamSourceType SourceType1 { get; set; }
    [Required]
    public TeamSourceType SourceType2 { get; set; }
    public virtual Match SourceMatch1 { get; set; }
    public virtual Match SourceMatch2 { get; set; }
}

For each of the two teams there is a TeamSourceType which indicates how the team is determined. If the TeamSourceType1/2 specifies the winner or loser of a previous match, I need the SourceMatch1/2 to reference the Match from which to get the winner/loser. I am using Entity Framework 6 Code First. I have tried several combinations of annotations and fluent mapping, but nothing has worked. I get "Multiplicity is not valid..." and "Multiplicity constraint violated...".

What annotations and/or fluent mappings do I need to make this work?

Upvotes: 1

Views: 53

Answers (1)

Murat Seker
Murat Seker

Reputation: 916

I had to use a self-referencing table in one of my projects and the way below worked for me. In my entity class, I defined FK like this.

public int? RelatedMatchId{ get; set; }
public virtual Match SourceMatch1 { get; set; }

Then, I added this specification to modelbuilder in OnModelCreating

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Match>()
        .HasOptional(c => c.SourceMatch1 )
        .WithMany()
        .HasForeignKey(c => c.RelatedMatchId);
}

Upvotes: 1

Related Questions