【问题标题】:Entity Framework 6 Code First Relationship/table creation issuesEntity Framework 6 Code First 关系/表创建问题
【发布时间】:2017-10-21 02:46:36
【问题描述】:

我正在尝试执行 Code First 迁移,但其中一个模型/表在我迁移时表现得非常奇怪。

Team and Tournament 制作了一个新表来参考哪个团队属于哪个锦标赛,反之亦然 - 这完全是我想要的。

我正在尝试对 Matchup 和 Team 做同样的事情,为两者定义集合,但由于某种原因,它在 Matchup 中创建了一个属性 TeamId,这是一个问题,因为 Matchup 应该能够存储多个团队。

Screenshots for clarity

提前致谢。

【问题讨论】:

  • 请在您的描述中更清楚。从您的问题陈述中无法得出什么结论。
  • 这就是一对多关系的运作方式。父ID(团队ID)作为外键存储在子(对战)中。
  • 很抱歉 Lakshmi - 我觉得很难说:(
  • @SteveGreene 但我在 Team 中定义了一组 Matchup 和一组在 Matchup 中的 Teams。那不应该是多对多的关系还是我错过了什么?
  • 其实你的配置看起来是正确的,EF应该已经在数据库中创建了一个叫MatchupTeam或TeamMatchup的出价表。您在 Matchup 中引用的 TeamID 用于获胜者导航属性。

标签: c# entity-framework


【解决方案1】:

当您在同一个文件中有多个引用时,您需要告诉 EF 如何处理关系。我更喜欢流畅的代码:

修复模型:

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

但是你也可以用注解来做到这一点:

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

【讨论】:

  • 知道了 - Matchups 集合中的 InverseProperty 和 Matchup 中的 WinnerId 起到了作用。非常感谢史蒂夫 :)
猜你喜欢
  • 2014-04-06
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多