Foreign key constraint may cause cycles or multiple cascade paths?

后端 未结 9 1282
感情败类
感情败类 2020-11-21 23:07

I have a problem when I try to add constraints to my tables. I get the error:

Introducing FOREIGN KEY constraint \'FK74988DB24B3C886\' on table \'Empl

9条回答
  •  伪装坚强ぢ
    2020-11-21 23:49

    This is because Emplyee might have Collection of other entity say Qualifications and Qualification might have some other collection Universities e.g.

    public class Employee{
    public virtual ICollection Qualifications {get;set;}
    

    }

    public class Qualification{
    
    public Employee Employee {get;set;}
    
    public virtual ICollection Universities {get;set;}
    

    }

    public class University{
    
    public Qualification Qualification {get;set;}
    

    }

    On DataContext it could be like below

    protected override void OnModelCreating(DbModelBuilder modelBuilder){
    
    modelBuilder.Entity().HasRequired(x=> x.Employee).WithMany(e => e.Qualifications);
    modelBuilder.Entity.HasRequired(x => x.Qualification).WithMany(e => e.Universities);
    

    }

    in this case there is chain from Employee to Qualification and From Qualification to Universities. So it was throwing same exception to me.

    It worked for me when I changed

        modelBuilder.Entity().**HasRequired**(x=> x.Employee).WithMany(e => e.Qualifications); 
    

    To

        modelBuilder.Entity().**HasOptional**(x=> x.Employee).WithMany(e => e.Qualifications);
    

提交回复
热议问题