0

I have played with Entity Framework 4.3 migrations for some time now, but I have trouble achieving the next behavior: In case my code runs on an existing database, I want the database to be migrated automatically to the latest version, but in case the database doesn't exist, the database should be created automatically from the migrations.

I think the problems is related to the first migration that you create. If you create the first migration using -IgnoreChanges parameter (or manually delete them as explained here: http://thedatafarm.com/blog/data-access/using-ef-migrations-with-an-existing-database/), you will not be able to use migrations in order to create a new table using the DbMigrator class. because you don't have the initial migration. If you create the first migration without using -IgnoreChanges, than the migration of the existing database will not be possible. Does anybody has any solution for this problem?

4

1 回答 1

0

所以你有现有的数据库,你想在该数据库上使用迁移,同时你想在新部署的情况下支持通过迁移创建数据库?

它看起来有点不受支持的用例。在这种情况下(未测试)最简单的方法是条件编译或由某些 AppSettings 键驱动的条件迁移。这意味着创建初始迁移,就好像您没有数据库并将 Up 方法修改为:

public override void Up() {
    if (ConfigurationManager.AppSettings["NewDatabaseRequired"] == "true") {
        // Here is generated content
    }
}

或者

public override void Up() {
#if NewDatabaseRequired
    // Here is generated content
#endif
}

还有许多其他更复杂的选项,包括为当前数据库编写脚本、修改脚本以在表已经存在时结束、将脚本作为资源添加到迁移程序集并在使用Up生成的方法中执行脚本-IgnoreChanges

作为另一个选项,您可以打开其他数据库连接并检查迁移的表是否已经存在(通过查询sys.tablesSQL Server 中的视图)。这将不需要生成的脚本。

于 2012-07-04T16:28:41.390 回答