How to configure a One-to-Many relationship in EF

二次信任 提交于 2019-11-28 13:24:51

If you want to create an one-to-many relationship between those two entities your model would be like this:

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;}
}

And the Fluent Api configuration would be:

modelBuilder.Entity<Image>()
            .HasOptional(i=>i.PageConfig)
            .WithMany(pc=>pc.ScrollerImages)
            .HasForeignKey(i=> i.PageConfigId);

If you idea is create an unidirectional one-to-many relationship then delete the FK and the navigation property on Image entity and configure the relationship this way:

modelBuilder.Entity<PageConfig>()
            .HasMany(pc => pc.ScrollerImages)
            .WithOptional();

Check this link for more info about this kind of relationship

Per http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx:

"...you can use Fluent API to configure a One-to-Many relationship using Student entity classes as shown below."

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);

    }

"...Use HasOptional method instead of HasRequired method to make foreign key column nullable."

So you'd be looking for something like this:

modelBuilder.Entity<Image>()
            .HasOptional<PageConfig>(x => x.PageConfig)
            .WithMany(x => x.ScrollerImages)
            .HasForeignKey(x => x.PageConfigId)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!