[英]EF Code-First many-to-many migration ignoring Link-Table specification
I have attempted to add a new many-to-many relationship between 2 tables in my db model. 我试图在数据库模型的2个表之间添加新的多对多关系。 The generated migration is ignoring the link table I have specified and instead added a foreign key to the left-side table. 生成的迁移将忽略我指定的链接表,而是向左侧表添加了外键。 How can I fix this? 我怎样才能解决这个问题?
I have used the same specification format for other many-to-many relationships that worked fine. 对于其他效果很好的多对多关系,我使用了相同的规范格式。
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");
});
The resulting migration is: 产生的迁移是:
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");
}
I don't understand why it is creating the new foreign-key column on Brand instead of just the link-table. 我不明白为什么它会在Brand上创建新的外键列,而不仅仅是链接表。
Problem is in the .WithMany()
. 问题在.WithMany()
。 You have explicit navigation property but you did not specify it in .WithMany()
. 您具有显式导航属性,但未在.WithMany()
指定它。
So write your configuration as follows: 因此,如下编写您的配置:
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");
});
Now it will generate everything as expected! 现在,它将生成预期的一切!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.