【问题标题】:Error occurring in Entity Framework in ASP.NET MVC while connecting to database连接到数据库时,ASP.NET MVC 中的实体框架中发生错误
【发布时间】:2016-02-21 20:37:58
【问题描述】:

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 'Courses' 没有定义键。定义此 EntityType 的键。
Courses: EntityType: EntitySet 'Courses' 基于没有定义键的类型'Courses'。

【问题讨论】:

  • 如果您对标识符使用一致的命名,例如为所有标识符使用ID,会发生什么情况?

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


【解决方案1】:

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

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

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

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

如果您不喜欢使用数据注释(上述方法),您可以使用 fluent 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);
  }
}

【讨论】:

  • 敏锐的眼光!当然建议使用单数名称。
  • 谢谢你,它成功了。我从 CourseID 更改为 CoursesID
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多