我正在使用 Entity Framework 4.1 制作一个 MVC3 Web 应用程序。问题是我有一个循环引用并且我得到了一个例外。我明白为什么这是错误的,所以我想从我的多对多关系中删除 ON DELETE/UPDATE CASCADE。问题是我不知道该怎么做......这就是我的问题的描述。这是我的模型:
问题->-。
| |
| |
/|\ |
领域 |
| |
| |
/|\ |
答案-----'
每个问题都有多个字段,每个字段都有多个答案。当我删除一个问题或答案时,我想删除相应的答案。我认为这里不需要做额外的工作。但是,每个答案都可以有多个从属问题(每个问题都可以依赖于许多答案)。这种关系仅在其他问题的答案为“是”时才用于显示问题,例如...现在,如果我删除一个答案,我不想删除所有依赖于它的问题,只删除依赖项。
在我的模型中,问题对象具有:
' VB
Public Overridable Property AnswerDependencies As List(Of QuestionAnswer)
// C#
public virtual List < QuestionAnswer > AnswerDependencies { get; set; }
QuestionAnswer 对象有:
' VB
Public Overridable Property DependentQuestions As List(Of Question)
// C#
public virtual List < Question > DependentQuestions { get; set; }
如何在具有以下属性的 DataContext 类中定义 OnModelCreating 事件中的预期行为:
Public Property Questions As DbSet(Of Question)
Public Property QuestionFields As DbSet(Of QuestionField)
Public Property QuestionAnswers As DbSet(Of QuestionAnswer)
编辑
我找到了解决问题的方法!我手动创建了 QuestionAnswerDependency 对象,如下所示:
Public Class QuestionAnswerDependency
Inherits ModelBase
Public Property QuestionId As Integer?
Public Overridable Property Question As Question
Public Property AnswerId As Integer
Public Overridable Property Answer As QuestionAnswer
Sub New(ByRef q As Question, ByRef a As QuestionAnswer)
Me.New()
Me.Question = q
Me.Answer = a
End Sub
Sub New()
End Sub
End Class
我将 QuestionId 属性设置为可为空,这导致 DELETE 上没有 CASCADE 并解决了循环引用。现在 Question 和 QuestionAnswer 对象有一个 QuestionAnswerDependency 对象列表:
Public Overridable Property QuestionAnswerDependencies As List(Of QuestionAnswerDependency)
我认为 EF 无法自动执行我想要的操作,但如果您知道如何在不创建“中间对象”的情况下实现这一目标,请告诉我。