在一对多关系中生成模型期间的验证错误

时间:2015-02-16 15:24:27

标签: asp.net-mvc entity-framework

当我运行应用程序时出现此错误:

  

PossibleAnswer_Question_Source ::多重性在角色中无效   ' PossibleAnswer_Question_Source'谈恋爱   ' PossibleAnswer_Question&#39 ;.因为依赖角色属性是   不是关键属性,多重性的上限   依赖角色必须是' *'。

如何解决?

QuestionPossibleAnswer的模型类:

public class Question
    {
        public int ID { get; set; }
        public string Text { get; set; }
        public bool IsAssociatedWithProfessor { get; set; }
        public bool IsAssociatedWithAssistant { get; set; }

        public virtual ICollection<PossibleAnswer> PossibleAnswers { get; set; }
    }
public class PossibleAnswer
    {
        public int ID { get; set; }
        public string Text { get; set; }
        public int QuestionID { get; set; }

        [ForeignKey("QuestionID")]
        public virtual Question Question { get; set; }
    }

我把它放在OnModelCreating(DbModelBuilder modelBuilder)

modelBuilder.Entity<PossibleAnswer>()
               .HasRequired(f => f.Question)
               .WithRequiredDependent()
               .WillCascadeOnDelete(false);

1 个答案:

答案 0 :(得分:1)

问题是您没有在OnModelCreating方法中配置一对多关系(即一对一配置)。为了达到你想要的效果,你可以这样做:

modelBuilder.Entity<PossibleAnswer>()
           .HasRequired(pa => pa.Question)
           .WithMany(q=>q.PossibleAnswers)
           .HasForeignKey(pa=>pa.QuestionID)
           .WillCascadeOnDelete(false);

这样,您无需在ForeignKey导航属性上使用Question属性。尝试不将Fluent Api与数据注释合并是一种好的做法