实体框架4.1代码优先和永久表在数据库中

本文关键字:数据库 框架 代码 实体 | 更新日期: 2023-09-27 18:04:13

我有一个永久存储美国邮政编码和城市名称列表的表。不幸的是,在EF 4.1中,如果我在开发期间修改模型,整个数据库需要被删除并重新创建。由于EF中还不支持迁移,这似乎是一个问题。什么好主意吗?

实体框架4.1代码优先和永久表在数据库中

您可以使用自定义初始化器类。在这里,您可以在数据库发生更改时插入所有值。这是来自Contoso大学的例子,来自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();

    }
 }

实际上第一个CTP版本的迁移已经可用,但它仍然只是预览。