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

后端 未结 2 1796
眼角桃花
眼角桃花 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:10

    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 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()
                .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()
                .HasMany(pc => pc.ScrollerImages)
                .WithOptional();
    

    Check this link for more info about this kind of relationship

提交回复
热议问题