1

I am working on asp.net mvc. I am trying to implement Code-First Entity Model. I have follwed the following steps,

1, I have created a class student.cs

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public string Branch { get; set; }
    public decimal Marks { get; set; }
    public string Address { get; set; }
}

2, I have craeted context class like,

 public class StudentContext:DbContext
    {
        public StudentContext()
        {
            Database.SetInitializer(new StudentContextInitializer());
        }

        public DbSet<Student> Student { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }

3, I have created studentcontextinitializer class like,

public class StudentContextInitializer : DropCreateDatabaseIfModelChanges<StudentContext>
    {
        protected override void Seed(StudentContext context)
        {
            context.Student.Add(new Student { StudentName="madhav",Branch="CSE",Marks=888,Address="AKP" });
            context.Student.Add(new Student { StudentName = "Tirumalesh", Branch = "IT", Marks = 988, Address = "MDP" });
            context.Student.Add(new Student { StudentName = "Venkat", Branch = "ECE", Marks = 1000, Address = "BZA" });
            context.SaveChanges();
        }
    }

I am successfully connected to database but i am unable to initialize the dbcontext with some data that means I have hard coded some records in studentcontextinitializer class but i am unable to bind that records into database table. so please guide me.

1
  • Drop your db and try again. Either that, or extend from DropCreateDatabaseAlwaysInitializer. Commented Oct 17, 2012 at 15:30

1 Answer 1

2

Your DropCreateDatabaseIfModelChanges will only initialize the db when you change the model. You have a couple of options:

  1. Delete the database manually and re-run.
  2. Change a model property. For example, add public string test { get; set; } to your Student entity and re-run.
  3. Extend your initializer from DropCreateDatabaseAlwaysInitializer. This will cause the db to be deleted, recreated, and seeded each time you rebuild and re-run your app.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.