1

我正在研究 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 类中硬编码了一些记录,但我无法将这些记录绑定到数据库表中。所以请指导我。

4

1 回答 1

2

DropCreateDatabaseIfModelChanges只会在更改模型时初始化数据库。你有几个选择:

  1. 手动删除数据库并重新运行。
  2. 更改模型属性。例如,添加public string test { get; set; }到您的Student实体并重新运行。
  3. DropCreateDatabaseAlwaysInitializer. 这将导致每次重建和重新运行应用程序时删除、重新创建和播种数据库。
于 2012-10-17T15:31:53.567 回答