我目前正在开发一个适用于动态调查表的应用程序。在数据库中定义的表单,如下所示:表单 > 部分 > 控件 > 问题。
每个问题可以有许多业务规则,例如:required、minlength、maxlength 等。
每个 BusinessRule 都是针对一个 Question 的规则。但是,有一些复杂的业务规则需要获取另一个问题的值。因此,每个业务规则可以有许多链接问题以从中获取所需的值。
我第一次使用代码,并为这种关系定义了以下类和映射:
public class Question
{
public int Id { get; set; }
public string Name { get; set; }
public int ValueTypeId { get; set; }
public int ParentQuestionId { get; set; }
public virtual ValueType ValueType { get; set; }
public virtual ICollection<Question> ChildQuestions { get; set; }
public virtual ICollection<BusinessRule> BusinessRules { get; set; }
public virtual ICollection<BusinessRule> LinkedBusinessRules { get; set; }
}
public class BusinessRule
{
public int Id { get; set; }
public string ValidationMessage { get; set; }
public string ConditionValue { get; set; }
public int QuestionId { get; set; }
public int BusinessRuleTypeId { get; set; }
public virtual BusinessRuleType BusinessRuleType { get; set; }
public virtual Question Question { get; set; }
public virtual ICollection<Question> LinkedQuestions { get; set; }
}
internal class QuestionConfigruation : EntityTypeConfiguration<Question>
{
public QuestionConfigruation()
{
this.HasMany<Question>(q => q.ChildQuestions)
.WithOptional()
.HasForeignKey(q => q.ParentQuestionId);
this.HasMany(q => q.BusinessRules)
.WithRequired(br => br.Question)
.WillCascadeOnDelete(false);
}
}
internal class BusinessRuleConfiguration : EntityTypeConfiguration<BusinessRule>
{
public BusinessRuleConfiguration()
{
this.HasMany(b => b.LinkedQuestions)
.WithMany(q => q.LinkedBusinessRules)
.Map(map =>
{
map.ToTable("BusinessRuleLinkedQuestions");
map.MapLeftKey("LinkedQuestionId");
map.MapRightKey("BusinessRuleId");
});
}
}
这导致在数据库中生成以下内容:
最后,我的问题:
[解决]
为什么多对多连接表忽略了我在 BusinessRuleConfiguration 中指定的表名和键的映射?
[/解决]
当我尝试通过执行以下操作使用自定义初始化程序插入测试表单时:
var companyName = new Question
{
Name = "CompanyName",
ValueTypeId = _typeRepository.GetValueType(ValueTypes.String).Id,
BusinessRules = new List<BusinessRule>{
new BusinessRule
{
BusinessRuleTypeId = _typeRepository.GetBusinessRuleType(BusinessRuleTypes.required).Id,
ValidationMessage = "Company name is required.",
}
}
};
var form = new Form
{
Sections = new List<Section>
{
new Section(){
Controls = new List<Control>
{
new Control{
ControlTypeId = _typeRepository.GetControlType(ControlTypes.Textbox).Id
Questions = new List<Question>
{
companyName,
}
}
}
}
}
}
我收到以下错误:
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
我在这个问题上花费了太长时间,现在试图解决它,因此非常感谢对 EF 和 Code First 有更多经验的人的帮助。我开始后悔选择代码优先,但我不知道是代码优先还是我对它的理解。
谢谢!