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

后端 未结 2 1793
眼角桃花
眼角桃花 2020-12-11 15:38

I have the following model

public class PageConfig : Base
{
    // Properties Etc..

    public ICollection ScrollerImages { get; set; }
}
         


        
2条回答
  •  失恋的感觉
    2020-12-11 16:00

    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()
                            .HasRequired(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()
                .HasOptional(x => x.PageConfig)
                .WithMany(x => x.ScrollerImages)
                .HasForeignKey(x => x.PageConfigId)
    

提交回复
热议问题