C#实体框架代码首次迁移错误,尽管实际上已定义密钥,但未定义密钥

时间:2019-01-20 09:36:33

标签: c# entity-framework ef-code-first key ef-migrations

我正在使用Entity Framework代码优先方法。在运行Update-Database -scriptenable-migrations之后在空白数据库中运行add-migration时出现以下错误:

  

standardvba.DataAccessLayer.LessonQuestion::EntityType'LessonQuestion'没有定义键。定义此EntityType的键。
  LessonQuestions:EntityType:EntitySet'LessonQuestions'基于未定义键的'LessonQuestion'类型。

LessonQuestion.cs

public partial class LessonQuestion
{
    public LessonQuestion()
    {
        this.LessonQuestionDetails = new List<LessonQuestionDetail>();
    } 

    [Key]
    public int QuestionID; // Key is defined

    public int OrderNumber;

    [ForeignKey("ParentQuestion")]
    public int ParentQuestionID;  

    [ForeignKey("Lesson")]
    public int LessonID { get; set; }

    [ForeignKey("ActionedBy")]    
    public int ActionedByUserID { get; set; }
    [MaxLength(1000)]
    public string Question { get; set; } 
    public bool IsApproved { get; set; }

    [Required]  // Sets the CASCADE constraint, while creating table
    public virtual CourseLesson Lesson { get; set; }

    public virtual SiteUser ActionedBy { get; set; }

    public virtual ICollection<LessonQuestionDetail> LessonQuestionDetails { get; set; }

    public virtual LessonQuestion ParentQuestion { get; set; }
}

我尝试了删除和重新创建Migrations文件夹之类的选项,但这没用。

1 个答案:

答案 0 :(得分:5)

密钥必须为Public Property。就您而言,这是一个字段。您需要进行以下更改

[Key]
public int QuestionID{get;set;}