You need to tell EF how to do the relationships when you have multiple references in the same file. I prefer fluent code for this:
Fix models:
public class Matchup
{
public int Id { get; set; }
public int WinnerId { get; set; } // FK by convention
public Team Winner { get; set; }
public Tournament Tournament { get; set; }
public ICollection<Team> Teams { get; set; }
}
public class Team
{
public int Id { get; set; }
public ICollection<Player> Players{ get; set; }
public ICollection<Matchup> Matchups{ get; set; }
public ICollection<Matchup> MatchupWinners{ get; set; }
public ICollection<Tournament> Tournaments{ get; set; }
}
// Configure 1 to many
modelBuilder.Entity<Matchup>()
.HasOptional(m => m.Winner)
.WithMany(p => p.MatchupWinners)
.HasForeignKey(p => p.WinnerId);
// Configure many to many
modelBuilder.Entity<Matchup>()
.HasMany(s => s.Teams)
.WithMany(c => c.Matchups)
.Map(t =>
{
t.MapLeftKey("MatchupId");
t.MapRightKey("TeamId");
t.ToTable("MatchupTeam");
});
But you can also do it with annotations:
public class Team
{
public int Id { get; set; }
public ICollection<Player> Players{ get; set; }
[InverseProperty("Teams")]
public ICollection<Matchup> Matchups{ get; set; }
[InverseProperty("Winner")]
public ICollection<Matchup> MatchupWinners{ get; set; }
public ICollection<Tournament> Tournaments{ get; set; }
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…