[英]How to configure one-to-many relationship with navigation property only on one side (on collection side) with EF Core 5?
[英]How to configure a One-to-Many relationship in EF
我有以下型號
public class PageConfig : Base
{
// Properties Etc..
public ICollection<Image> ScrollerImages { get; set; }
}
我的方法是使用聯結表{PageConfigID,ImageID}進行綁定。
在我的模型資料夾中,我嘗試了以下方法。
modelBuilder.Entity<PageConfig>()
.HasMany(x => x.ScrollerImages)
.WithMany()
.Map(x =>
{
x.ToTable("junc_PageConfigScrollerImages");
x.MapLeftKey("PageConfigID");
x.MapRightKey("ImageID");
});
這將導致圖像的空集合。
如何將這些圖像綁定到PageConfig模型?
編輯
大多數問題是由於用戶錯誤。 jic這發生在你身上..
檢查數據庫中的關鍵約束是否正確設置。
模型上的ICollection需要為虛擬的。
如果要在這兩個實體之間創建一對多關系,則模型將如下所示:
public class PageConfig
{
public int Id {get;set;}
//navigation property
public ICollection<Image> ScrollerImages {get;set;}
}
public class Image
{
public int Id {get;set;}
//FK
public int? PageConfigId {get;set;}
//navigation property
public PageConfig PageConfig {get;set;}
}
Fluent Api配置為:
modelBuilder.Entity<Image>()
.HasOptional(i=>i.PageConfig)
.WithMany(pc=>pc.ScrollerImages)
.HasForeignKey(i=> i.PageConfigId);
如果您想創建一個單向一對多關系,則刪除Image
實體上的FK和navigation屬性,並通過以下方式配置該關系:
modelBuilder.Entity<PageConfig>()
.HasMany(pc => pc.ScrollerImages)
.WithOptional();
檢查此鏈接以獲取有關這種關系的更多信息
“ ...您可以使用Fluent API使用學生實體類來配置一對多關系,如下所示。”
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//one-to-many
modelBuilder.Entity<Student>()
.HasRequired<Standard>(s => s.Standard)
.WithMany(s => s.Students)
.HasForeignKey(s => s.StdId);
}
“ ...使用HasOptional方法而不是HasRequired方法來使外鍵列可為空。
因此,您將尋找這樣的東西:
modelBuilder.Entity<Image>()
.HasOptional<PageConfig>(x => x.PageConfig)
.WithMany(x => x.ScrollerImages)
.HasForeignKey(x => x.PageConfigId)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.