For some reason, only the data for Student is being generated inside the Student's table. However, the enrollment and course tables have no data inside them, even though I am adding them in the SchoolInitializer. Am I missing something? Any suggestions? When launching my application, I would close the connection to my database, rebuild solution, and then start without debugging, click the link where the data is being created, and then check my tables.
namespace MyFirstWebApplication.Models
{
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("2014-01-02") },
new Student{FirstName = "Lynda", LastName = "Thames", EnrollmentDate = DateTime.Parse("2013-11-02")}
};
foreach (var temp in students)
{
context.Students.Add(temp);
}
context.SaveChanges();
var courses = new List<Course>
{
new Course{CourseName = "Java", TotalCredits = 4},
new Course{CourseName = "C#", TotalCredits = 4}
};
foreach (var temp in courses)
{
context.Courses.Add(temp);
}
context.SaveChanges();
var enrollments = new List<Enrollment>
{
new Enrollment{StudentId = 1, CourseId = 1, Grade = 3},
new Enrollment{StudentId = 1, CourseId = 2, Grade = 4}
};
foreach (var temp in enrollments)
{
context.Enrollments.Add(temp);
}
context.SaveChanges();
}
}
}
namespace MyFirstWebApplication.Models
{
public class SchoolContext : DbContext
{ //enables CRUD functionality
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
namespace MyFirstWebApplication
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer<SchoolContext>(new SchoolInitializer() );
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}