【发布时间】:2019-12-19 01:36:56
【问题描述】:
我在映射以下类时遇到问题。
我希望MainAboutPage 是可选的(一对零或一),而AboutSubPages 显然是一对多的。
理想情况下,我想将WebsiteId 属性保留在WebsitePage 类上。
public class Website
{
public int Id { get; set; }
public virtual WebsitePage MainAboutPage { get; set; }
public ICollection<WebsitePage> AboutSubPages { get; set; }
}
public class WebsitePage
{
public int Id { get; set; }
public int WebsiteId { get; set; }
public virtual Website Website { get; set; }
}
当我不使用流畅的映射时,我会得到
无法确定关系的主体端。多个添加的实体可能具有相同的主键。
当我使用这个流畅的映射时:
modelBuilder.Entity<Wesbite>()
.HasMany(x => x.AboutSubPages)
.WithRequired(x => x.Website)
.HasForeignKey(x => x.WebsiteId);
我明白了:
无法确定“Wesbite_AboutSubPages”关系的主体端。多个添加的实体可能具有相同的主键。
当我使用这个流畅的映射时:
modelBuilder.Entity<Website>()
.HasOptional(x => x.MainAboutPage)
.WithRequired();
modelBuilder.Entity<Wesbite>()
.HasMany(x => x.AboutSubPages)
.WithRequired(x => x.Website)
.HasForeignKey(x => x.WebsiteId);
我明白了:
无法确定“Website_MainAboutPage”关系的主体端。多个添加的实体可能具有相同的主键。
当我使用这个流畅的映射时:
modelBuilder.Entity<Website>()
.HasOptional(x => x.MainAboutPage)
.WithRequired(x => x.Website);
modelBuilder.Entity<Wesbite>()
.HasMany(x => x.AboutSubPages)
.WithRequired(x => x.Website)
.HasForeignKey(x => x.WebsiteId);
我明白了:
Wesbite_MainAboutPage_Target: : 多重性在关系“Website_MainAboutPage”中的角色“Wesbite_MainAboutPage_Target”中无效。因为从属角色属性不是关键属性,所以从属角色的多重性的上限必须是'*'。
我一直在无休止地阅读 MS 的配置示例:https://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx 和 https://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx
我的大脑被腌制了,如果我遗漏了一些明显的东西,请原谅我。我真的很感激一些关于我想要的设置的指示。
提前致谢。
【问题讨论】:
标签: asp.net-mvc entity-framework one-to-many ef-fluent-api fluent-interface