Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

c# - Entity Framework 6 Code First Relationship/table creation issues

I'm trying to do a Code First migration, but one of the models/tables behave pretty weird when I migrate.

Team and Tournament makes a new Table to reference what team belongs to what tournament and the other way around - That's totally what I want.

I'm trying to do the same with Matchup and Team, defining collections for both, but for some reason it makes a single property, TeamId, in Matchup which is a problem since a Matchup should be able to store more than one Team.

Screenshots for clarity

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...