Reputation: 1851
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.
Upvotes: 1
Views: 1535
Reputation: 47375
Your DropCreateDatabaseIfModelChanges
will only initialize the db when you change the model. You have a couple of options:
public string test { get; set; }
to your Student
entity and re-run.DropCreateDatabaseAlwaysInitializer
. This will cause the db to be deleted, recreated, and seeded each time you rebuild and re-run your app.Upvotes: 2