当我运行应用程序时出现此错误:
PossibleAnswer_Question_Source ::多重性在角色中无效 ' PossibleAnswer_Question_Source'谈恋爱 ' PossibleAnswer_Question&#39 ;.因为依赖角色属性是 不是关键属性,多重性的上限 依赖角色必须是' *'。
如何解决?
Question
和PossibleAnswer
的模型类:
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);
答案 0 :(得分:1)
问题是您没有在OnModelCreating
方法中配置一对多关系(即一对一配置)。为了达到你想要的效果,你可以这样做:
modelBuilder.Entity<PossibleAnswer>()
.HasRequired(pa => pa.Question)
.WithMany(q=>q.PossibleAnswers)
.HasForeignKey(pa=>pa.QuestionID)
.WillCascadeOnDelete(false);
这样,您无需在ForeignKey
导航属性上使用Question
属性。尝试不将Fluent Api与数据注释合并是一种好的做法