连接到数据库

时间:2016-02-21 20:37:59

标签: c# asp.net-mvc entity-framework

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

错误详情:

  

在模型生成期间检测到一个或多个验证错误:
  DAL.Courses :: EntityType&#39;课程&#39;没有定义键。定义此EntityType的键   课程:实体类型:实体集&#39;课程&#39;是基于类型&#39;课程&#39;没有定义键。

1 个答案:

答案 0 :(得分:3)

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

将您的实体类名称更改为Course或将CourseID属性更改为CoursesID

另一个选择是使用CourseID数据注释装饰您的[Key]媒体资源。

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);
  }
}
相关问题