1

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);
        }
    }
}
LinhSaysHi
  • 642
  • 5
  • 14
  • 30
  • okay, I found the problem. It is this method: protected override void OnModelCreating This method stopped me from updating my tables and data. Any reasons why? For example, I added a new Student for the list of students in the SchoolInitializer. Rebuild and started without debugging and my page did not update with the new student. I commented out the method and rebuild and started without debugging and the list updated along with my tables in database – LinhSaysHi May 10 '15 at 03:27

2 Answers2

1

Try calling context.SaveChanges() only once, at the end.

Also check out following SO questions/answers:

Multiple SaveChanges Calls in Entity Framework

Call SaveChanges twice inside transaction

Community
  • 1
  • 1
CrnaStena
  • 3,017
  • 5
  • 30
  • 48
  • I've made this change, however there is still no data within my Enrollment and Course table. I'll get back to you when I'm done looking at the links you have provided – LinhSaysHi May 08 '15 at 23:45
0

If you are using Identity field for keys, you should get the generated database keys. For example, you should use:

var newStudent = context.Students.Add(new Student{...});
context.SaveChanges();
var newStudentId = newStudent.StudentId

Then you can use this id to insert your enrollments. Something like that:

context.Enrollments.Add(new Enrollment{StudentId = newStudentId, CourseId = 1, Grade = 3});

The other thing you have to take into account is that the Seed method do the call to savechanges method.

You should review the AddOrReplace method. It is the preferred method to insert data for seeds the database.

daniel
  • 26
  • 2
  • For using the generated database keys, will that even make any difference? Seems more like a 'better practice' kind of advice haha. Is that a typo? You said "The other thing you to take into account is that the seed method do... " Are you saying the seed method does the call so I don't have to explicitly say it? Not really sure – LinhSaysHi May 08 '15 at 23:59