我正在研究 asp.net mvc。我正在尝试实现代码优先实体模型。我已按照以下步骤操作,
1、我创建了一个类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,我已经创建了上下文类,例如,
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,我创建了 studentcontextinitializer 类,例如,
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();
}
}
我已成功连接到数据库,但我无法用一些数据初始化 dbcontext,这意味着我在 studentcontextinitializer 类中硬编码了一些记录,但我无法将这些记录绑定到数据库表中。所以请指导我。