【发布时间】:2016-04-12 10:58:26
【问题描述】:
我有一个问题。 我有一些看起来像这样的类:
public class Question
{
public int Id { get; set; }
[Required] [MaxLength(255)] public string Text { get; set; }
public int CriteriaId { get; set; }
public int QuestionGroupId { get; set; }
public QuestionGroup QuestionGroup { get; set; }
public virtual IList<Answer> Answers { get; set; }
public virtual Criteria Criteria { get; set; }
}
public class Answer
{
public int Id { get; set; }
[Required] [MaxLength(255)] public string Text { get; set; }
public int QuestionId { get; set; }
public Question Question { get; set; }
public virtual IList<State> States { get; set; }
}
public class Criteria
{
public int Id { get; set; }
[Required] [MaxLength(100)] public string Name { get; set; }
public virtual IList<State> States { get; set; }
public IList<Question> Questions { get; set; }
}
public class State
{
public int Id { get; set; }
public int CriteriaId { get; set; }
[Required] [MaxLength(100)] public string Name { get; set; }
public int Score { get; set; }
public virtual IList<Filter> Filters { get; set; }
public Criteria Criteria { get; set; }
}
他们有一个多对多的关系,所以我创建了这个映射:
modelBuilder.Entity<Answer>()
.HasMany(m => m.States)
.WithMany()
.Map(m => {
m.MapLeftKey("AnswerId");
m.MapRightKey("StateId");
m.ToTable("AnswerStates");
});
当我尝试更新我的数据库时,我收到关于外键的错误。 所以我添加了这一行(作为临时修复):
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
但我需要级联删除。 我似乎无法弄清楚为什么它不会让我拥有它。 尝试包含级联删除时出现的错误是:
在表“AnswerStates”上引入 FOREIGN KEY 约束“FK_dbo.AnswerStates_dbo.States_StateId”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。
我希望我已经提供了足够的信息。有谁知道我可以做些什么来允许级联删除(我需要能够删除 State 或 Answer 并从 AnswerStates 中删除记录
【问题讨论】:
-
从帖子中没有直接看到,但似乎您有一些来自
Answer.Question和State.Criteria的常见级联删除路径。你能发布Question和Criteria模型吗? -
已添加,希望对您有所帮助
-
多级联路径是由
Criteria和Answer都具有States属性引起的,因此它们都尝试级联删除状态。此外,级联删除永远不会实现多对多。您必须在迁移中手动添加它,或者将关联更改为“1-n-1”,即将AnswerStates作为实体绘制到模型中。
标签: entity-framework