【问题标题】:Validation error during model generation in one-to-many relationship以一对多关系生成模型期间的验证错误
【发布时间】:2015-02-16 15:24:26
【问题描述】:

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

PossibleAnswer_Question_Source: : 多重性在角色中无效 关系中的“PossibleAnswer_Question_Source” '可能的答案_问题'。因为从属角色属性是 不是关键属性,多重性的上限 从属角色必须是“*”。

如何解决?

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);

【问题讨论】:

  • 尝试将[Key]属性添加到Question.ID属性,或将[InverseProperty("ID")]添加到PossibleAnswer.Question
  • 之后我得到这个:属性“ID”不能配置为导航属性。该属性必须是有效的实体类型,并且该属性应该具有非抽象的 getter 和 setter。对于集合属性,该类型必须实现 ICollection,其中 T 是有效的实体类型。
  • 抱歉,我没有注意到您在流利的映射中定义了 1:1 关系,所以请按照@octavioccl 的回答...当然,逆属性应该是[InverseProperty("PossibleAnswers ")],但是修复映射并添加[Key]属性时不需要它...

标签: asp.net-mvc entity-framework


【解决方案1】:

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

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

这样,您不需要在Question 导航属性上使用ForeignKey 属性。尽量不要将 Fluent Api 与 Data Annotations 合并是一个好习惯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2018-08-11
    • 2017-09-27
    • 1970-01-01
    • 2013-02-04
    相关资源
    最近更新 更多