Sujoy
Sujoy

Reputation: 1235

C# Entity Framework code first migration error, no key defined though key is actually defined

I am using Entity Framework code-first approach. I am getting the following error when I run Update-Database -script in a blank database, after running enable-migrations and add-migration:

standardvba.DataAccessLayer.LessonQuestion: : EntityType 'LessonQuestion' has no key defined. Define the key for this EntityType.
LessonQuestions: EntityType: EntitySet 'LessonQuestions' is based on type 'LessonQuestion' that has no keys defined.

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

I tried options like deleting and re-creating the Migrations folder, but that did not work.

Upvotes: 0

Views: 473

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18163

The Key needs to be Public Property. In your case, it is a field. You need to change it as following

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

Upvotes: 5

Related Questions