另一个在ASP MVC的传奇中tutorial我正在努力。一切都很顺利,除了,我注意到创建的三个表中有两个没有数据。无法弄清楚为什么,我认真地删除了数据库,以为我会从头开始重新创建它。好了,现在创建了数据库,但是没有表格。 AND,将在表中的数据仍然传递给视图。我很困惑。
SchoolContext.cs
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
....
....
SchoolInitializer.cs
public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>
{
protected override void Seed(SchoolContext context)
{
var students = new List<Student>()
{
new Student{FirstName = "James", LastName = "Dean", EnrollmentDate = DateTime.Parse("01/01/2015")},
new Student{FirstName = "Linda", LastName = "Thames", EnrollmentDate = DateTime.Parse("01/01/2015")}
};
foreach (var student in students)
{
context.Students.Add(student);
}
context.SaveChanges();
...And a Courses table and an Enrollment table...
XyzController.cs
public class XyzController : Controller
{
private SchoolContext db = new SchoolContext();
// GET: Xyz
public ActionResult Abc()
{
var students = db.Students.ToList();
答案 0 :(得分:1)
您是否正确设置了数据库初始化程序? 你需要这样的东西:
Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());
您应该将此行放在Global.asax中的Application_Start()方法中 如果是,您可以回收您的应用程序池以使此代码再次运行。