Entity framework 4.3 with required association

后端 未结 3 1867
南旧
南旧 2021-01-13 07:14

I\'m a very strange behavior with EF code first approach and associations. I have two entities:

public class GlobalKpiSectionn
{
    public GlobalKpiSection(         


        
3条回答
  •  情话喂你
    2021-01-13 07:36

    To force cascade deletes, you have to use the fluent configurations. You can then remove the [Required]attribute from the KpiSection property.

    Something like this:

    public class GlobalKpiSectionn
    {
        public GlobalKpiSection()
        {
            this.Regions = new HashSet();
        }
    
        public virtual ICollection Regions { get; protected set; }  
    }
    
    public class Region
    {
        public int RegionId { get; set; }
    
        public bool IsMain { get; set; }
    
        public int GlobalKpiSectionId { get; set; }
        public virtual GlobalKpiSection KpiSection { get; set; }
    }
    
    public class RegionConfig : EntityTypeConfiguration
    {
        HasRequired(x => x.KpiSection)
            .WithMany(x => x.Regions)
            .HasForeignKey(x => x.GlobalKpiSectionId)
            .WillCascadeOnDelete(true);
    }
    
    public class YourContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new RegionConfig());
        }
    }
    

提交回复
热议问题