简体   繁体   English

实体框架6代码优先关系/表创建问题

[英]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. 我正在尝试进行Code First迁移,但是其中一个模型/表在迁移时表现得很奇怪。

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. 我正在尝试对Matchup和Team进行相同的操作,为它们都定义了集合,但是由于某种原因,它在Matchup中只创建了一个属性TeamId,这是一个问题,因为Matchup应该可以存储多个Team。

Screenshots for clarity 截图清晰

Thanks in advance. 提前致谢。

You need to tell EF how to do the relationships when you have multiple references in the same file. 当同一文件中有多个引用时,您需要告诉EF如何建立关系。 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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM