EF代码优先的多对多迁移,忽略了链接表规范

时间:2019-05-13 15:22:02

标签: c# entity-framework ef-code-first ef-migrations

我试图在我的数据库模型中的2个表之间添加新的多对多关系。生成的迁移将忽略我指定的链接表,而是向左侧表添加了外键。我该如何解决?

对于很多正常工作的其他多对多关系,我使用了相同的规范格式。

public class Competitor
{
    [Key]
    public Guid ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get { return string.Format("{0} {1}", FirstName, LastName).Trim(); } }
    public bool IsMatchResult { get; set; }

    public virtual ICollection<Title> Titles { get; set; }
    public virtual ICollection<MatchParticipant> MatchesParticipated { get; set; }
    public virtual ICollection<MatchResult> MatchResults { get; set; }
    public virtual ICollection<TagTeam> TagTeams { get; set; }

    public virtual ICollection<Brand> Brands { get; set; }

}

public class Brand
{
    [Key]
    public Guid ID { get; set; }
    public string Name { get; set; }
    public Guid? ParentID { get; set; }

    [ForeignKey("ParentID")]
    public virtual Brand Parent { get; set; }
    public virtual ICollection<Event> Events { get; set; }

    public virtual ICollection<Competitor> Roster { get; set; }

}

modelBuilder.Entity<Brand>()
            .HasMany<Competitor>(c => c.Roster)
            .WithMany()
            .Map(mp =>
            {
                mp.MapLeftKey("BrandID");
                mp.MapRightKey("CompetitorID");
                mp.ToTable("BrandCompetitors");
            });

最终的迁移是:

    public override void Up()
    {
        CreateTable(
            "dbo.BrandCompetitors",
            c => new
                {
                    BrandID = c.Guid(nullable: false),
                    CompetitorID = c.Guid(nullable: false),
                })
            .PrimaryKey(t => new { t.BrandID, t.CompetitorID })
            .ForeignKey("dbo.Brand", t => t.BrandID, cascadeDelete: true)
            .ForeignKey("dbo.Competitor", t => t.CompetitorID, cascadeDelete: true)
            .Index(t => t.BrandID)
            .Index(t => t.CompetitorID);

        AddColumn("dbo.Brand", "Competitor_ID", c => c.Guid());
        CreateIndex("dbo.Brand", "Competitor_ID");
        AddForeignKey("dbo.Brand", "Competitor_ID", "dbo.Competitor", "ID");
    }

我不明白为什么它会在Brand上创建新的外键列,而不仅仅是链接表。

1 个答案:

答案 0 :(得分:1)

问题在.WithMany()中。您具有显式导航属性,但未在.WithMany()中指定它。

因此,请按如下所示编写配置:

modelBuilder.Entity<Brand>()
            .HasMany<Competitor>(b => b.Roster)
            .WithMany(c => c.Brands) // <-- Here it is
            .Map(mp =>
            {
                mp.MapLeftKey("BrandID");
                mp.MapRightKey("CompetitorID");
                mp.ToTable("BrandCompetitors");
            });

现在它将按预期生成所有内容!