c# - 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 上创建新的外键列,而不仅仅是链接表。
解决方案
问题出在.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");
});
现在它将按预期生成一切!
推荐阅读
- c# - Xunit (c#) - 有没有办法在测试类之间共享上下文而不禁用并行测试执行?
- delphi - 如何在delphi firemonkey中为floatanimation添加音效?
- git - 在 git 中管理与某些 API 相关的多个产品的多个版本
- flutter - 我如何在flutter android build中修复这个错误?
- flutter - Flutter Simple Dialog 内容离开屏幕
- database - 加快 Neo4j 关系创建
- javascript - CKeditor - 图片未显示在网站前端
- python - 简单的 Pandas 回溯问题
- java - 如何在不修改序列化类的情况下全局配置 spring-ws / spring-boot-starter-web-services 以序列化空(null)元素?
- dialogflow-es - Dialogflow 以正确的时态回复?