实体框架多对多关系错误
Posted
技术标签:
【中文标题】实体框架多对多关系错误【英文标题】:Entity Framework many to many relation error 【发布时间】:2018-05-11 05:15:46 【问题描述】:我正在尝试在我的两个表之间创建多对多关系,但是当我运行 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;
谁能告诉我哪里出错了?
【问题讨论】:
实体似乎没问题。你也有映射吗?该错误是从 SQL Server 引发的。开始迁移时您的数据库是否为空? 没有其他错误。就这一个。 关于映射? 【参考方案1】:默认情况下,EF 设置了级联删除。此错误警告您,这可能会导致具有多对多关系的级联删除。并且可能不是您打算在删除/更新时发生的事情。
您可以在OnModelCreating
方法中删除OneToManyCascadeDeleteConvention
,或者在每个实体的流利映射上删除。
Details are provided in this SO Answer
【讨论】:
以上是关于实体框架多对多关系错误的主要内容,如果未能解决你的问题,请参考以下文章