简体   繁体   中英

Why are code-first tables not being created using Entity framework?

Yet another in the saga of the ASP MVC tutorial I'm working through. Everything was going along pretty nicely, except, I noticed that two of the three tables being created had no data in them. Unable to figure out why, I got serious and deleted the database thinking I would let it be created again from scratch. Well, now the database is created, but has no tables in it. AND, data that would be in a table is still getting passed to the view. I'm very confused.

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

学生数据传递给查看

但是数据库中没有表

Do you have your Database Initializer setup correctly? You will need something like this:

Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());

You should put this line in the Application_Start() method in Global.asax If yes, you can recycle your app pool to make this code to run again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM