Entity framework 4.3 with required association

后端 未结 3 1865
南旧
南旧 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<Region>();
        }
    
        public virtual ICollection<Region> 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<Region>
    {
        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());
        }
    }
    
    0 讨论(0)
  • 2021-01-13 07:53

    EF disabled lazy loading when it validates the entities. It does this to avoid unnecessary round trips to database due to the validations placed on navigational properties.

    Model the scalar property in your entity and place the validation attribute there.

    public class Region
    {
        public int RegionId { get; set; }
    
        public bool IsMain { get; set; }
    
        [Required]
        public int? KpiSectionId { get; set; }
    
        public virtual GlobalKpiSection KpiSection { get; set; }
    }
    
    0 讨论(0)
  • 2021-01-13 08:00

    That is why you should not use data annotations. Data annotations are wrong feature because they do both mapping and validation (violation of single responsibility) - as you see it is not always what you want. So your current options are:

    • Turn off validation in context.Configuration.ValidateOnSaveEnabled = false
    • Expose non nullable KpiSectionId foreign key property in your Region entity (you will not need Required attribute on your navigation property).
    • Use fluent API instead of data annotations :

    Example:

    modelBuilder.Entity<GlobalKpiSection>()
                .WithMany(s => s.Regions)
                .HasRequired(r => r.KpiSection);
    
    0 讨论(0)
提交回复
热议问题