首页 > 解决方案 > EF Code-First 多对多迁移忽略链接表规范

问题描述

我试图在我的数据库模型中的 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 上创建新的外键列,而不仅仅是链接表。

标签: c#entity-frameworkef-code-firstentity-framework-migrations

解决方案


问题出在.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");
            });

现在它将按预期生成一切!


推荐阅读