首页 > 解决方案 > 实体框架多对多关系错误

问题描述

我正在尝试在两个表之间创建多对多关系,但是当我运行Update-Database命令时出现此错误:

在表“ExamQuestions”上引入 FOREIGN KEY 约束“FK_dbo.ExamQuestions_dbo.Questions_Question_Id”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。
无法创建约束或索引。请参阅以前的错误。

我的第一个实体是:

public class Question
{
   public Question()
   {
       this.Exams = new HashSet<Exam>();
   }

   [Key]
   public int Id { get; set; }

   [Required(ErrorMessage="Question is Required")]
   [Display(Name="Question")]
   [AllowHtml]
   public string QuestionText { get; set; }

   // public bool IsMultiSelect { get; set; }
   public string Hint { get; set; }
   public string HelpLink { get; set; }

   public int Marks { get; set; }
   public byte[] ImageData { get; set; }
   [StringLength(50)]
   public string MimeType { get; set; }
   public byte[] Audio { get; set; }

   public int QuestionTypeId { get; set; }
   public int TopicId { get; set; }
   public int DifficulityLevelId { get; set; }
   public int SubjectId { get; set; }

   public DifficultyLevel QuestionDifficulity { get; set; }
   public Topic Topic { get; set; }

   public virtual ICollection<Option> Options { get; set; }
   public ICollection<Exam> Exams { get; set; }
}

第二个实体是:

public class Exam
{
   public Exam()
   {
       this.Questions = new HashSet<Question>();
   }

   [Key]
   public int Id { get; set; }

   [Required]
   public string Name { get; set; }
   [Required]
   public int Duration { get; set; }
   [Required]
   public int TotalQuestion { get; set; }
   [Required]
   public int TotalMarks { get; set; }
   public bool SectionWiseTime { get; set; }
   public bool QuestionWiseTime { get; set; }
   public bool AllQustionRequired { get; set; }
   public bool AllowBackForward { get; set; }
   public bool SuffleSubjectWise { get; set; }
   public bool SuffleOptionWise { get; set; }
   public bool GroupSubjectWise { get; set; }

   [Required]
   public int ExamTypeId { get; set; }
   [Required]
   public int ExamInstructionId { get; set; }
   [Required]
   public int DifficultyLevelId { get; set; }

   public virtual ExamType ExamType { get; set; }
   public virtual ExamInstruction ExamInstruction { get; set; }
   public virtual DifficultyLevel DifficultyLevel { get; set; }

   public virtual  ICollection<Question> Questions { get; set; }
   //public virtual ICollection<ExamSchedule> ExamSchedules { get; set; }
}

有人可以告诉我哪里出错了吗?

标签: asp.netentity-frameworkasp.net-mvc-5many-to-many

解决方案


默认情况下,EF 设置了级联删除。此错误警告您,这可能会导致具有多对多关系的级联删除。并且可能不是您打算在删除/更新时发生的事情。

您可以OneToManyCascadeDeleteConventionOnModelCreating方法中删除 ,或在每个实体的流利映射上删除。

此 SO 答案中提供了详细信息


推荐阅读