连接到数据库时,ASP.NET MVC 中的实体框架中发生错误

本文关键字:实体 框架 错误 MVC 数据库 NET ASP 连接 | 更新日期: 2023-09-27 18:35:33

Student类 :

public class Students
{
        public int ID { get; set; }
        public string Fname { get; set; }
        public string Lname { get; set; }
        public DateTime EnrollmentDate { get; set; }
        //on one to many relationship Student can have many enrollments so its a collection of Enrollments
        public virtual ICollection<Enrollment> Enrollments { get; set; }
}

招生:

public enum Grade
{
    A, B, C, D, F
}
public class Enrollment
{    
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        //? will take the default value, to avoid null expections as object value not set, if the grade not above theen also passes with out any errors.
        public Grade? Grade { get; set; }
        //single enrollment has  single course , single we give the Courses as Class name 
        public virtual Courses Course { get; set; }
        //single enrollment has  single student, single we give the Student  as Class name 
        public virtual Students Student { get; set; }
}

Courses类 :

public class Courses
{
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
        // A course has many enrollments
        public virtual ICollection<Enrollment> Enrollments { get; set; }
}

Controller - 在

db.Students.Add(objstu)

当我第一次运行应用程序并希望查看自动生成的表时。但是当它连接到数据库时,我收到此错误

public ActionResult CreateStudent(Students objstu)
{
            if (!ModelState.IsValid)
            {
                return View(objstu);
            }
            db.Students.Add(objstu);     
            return View();
}

错误详细信息:

在模型生成过程中检测到一个或多个验证错误:
达尔。课程:实体类型"课程"未定义键。定义此实体类型的键。
课程:实体类型:实体集"课程"基于未定义键的类型"课程"。

连接到数据库时,ASP.NET MVC 中的实体框架中发生错误

您的实体类名称是 Courses 。但主键列名是 CourseID 。按照惯例,它应该是IDentity class name+ID,这是CoursesID

将实体类名称更改为CourseCourseID属性更改为CoursesID

另一种选择是使用[Key]数据注释装饰CourseID属性。

public class Courses
{
    [Key]
    public int CourseID { get; set; }
}

如果您不喜欢使用数据注释(上述方法),则可以使用流畅的 api 实现相同的目标。在数据上下文类中,重写 OnModelCreating 方法并指定哪一列是 Courses 实体类的键。

public class YourDbContext : DbContext
{ 
  public DbSet<Courses> Courses { set; get; }
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Courses>().HasKey(f => f.CourseID);
  }
}