C# Entity Framework 代码首次迁移错误,虽然实际定义了键但未定义键
C# Entity Framework code first migration error, no key defined though key is actually defined
我正在使用 Entity Framework 代码优先方法。在 运行ning enable-migrations
和 add-migration
:
之后,我在空白数据库中 运行 Update-Database -script
时出现以下错误
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; }
}
我尝试了删除和重新创建 Migrations
文件夹等选项,但没有用。
密钥必须是 Public Property
。在您的情况下,它是一个字段。你需要改变它如下
[Key]
public int QuestionID{get;set;}
我正在使用 Entity Framework 代码优先方法。在 运行ning enable-migrations
和 add-migration
:
Update-Database -script
时出现以下错误
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; }
}
我尝试了删除和重新创建 Migrations
文件夹等选项,但没有用。
密钥必须是 Public Property
。在您的情况下,它是一个字段。你需要改变它如下
[Key]
public int QuestionID{get;set;}