Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...