实体框架4.1代码数据库中的第一个永久表
问题描述:
我有一张表,可以永久保存美国邮政编码和城市名称列表。不幸的是,似乎在EF 4.1中,如果我在开发过程中修改模型,整个数据库需要被删除并重新创建。由于EF中尚未支持迁移,这似乎是一个问题。任何想法?
I have an table that permanently stores a list of zip codes and city names for the US. Unfortunately, it seems that with EF 4.1 if I modify the model during developement, the entire db needs to be droped and recreated. Since migrations are not yet supported in EF, this seems to be a problem. Any ideas?
答
您可以使用custome初始化程序类。在这里,您可以在数据库更改发生时插入所有值。这是来自msdn的Contoso Universty示例。
you can use a custome initializer class. In here you can insert all values when database changes happens. This is from Contoso Universty example from msdn.
public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>
{
protected override void Seed(SchoolContext context)
{
var students = new List<Student>
{
new Student { FirstMidName = "Carson", LastName = "Alexander", EnrollmentDate = DateTime.Parse("2005-09-01") },
new Student { FirstMidName = "Meredith", LastName = "Alonso", EnrollmentDate = DateTime.Parse("2002-09-01") },
new Student { FirstMidName = "Arturo", LastName = "Anand", EnrollmentDate = DateTime.Parse("2003-09-01") },
new Student { FirstMidName = "Gytis", LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2002-09-01") },
new Student { FirstMidName = "Yan", LastName = "Li", EnrollmentDate = DateTime.Parse("2002-09-01") },
new Student { FirstMidName = "Peggy", LastName = "Justice", EnrollmentDate = DateTime.Parse("2001-09-01") },
new Student { FirstMidName = "Laura", LastName = "Norman", EnrollmentDate = DateTime.Parse("2003-09-01") },
new Student { FirstMidName = "Nino", LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2005-09-01") }
};
students.ForEach(s => context.Students.Add(s));
context.SaveChanges();
}
}