【发布时间】: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