EF Code First 与另一个数据库上的现有数据库

EF Code First with existing database on another database

标题有点令人困惑,但我试图说明问题不是启动代码优先模型和现有数据库的迁移,而是之后出现的。

我需要激活自动迁移,因为我们的系统切换到了代码优先模型。所以,这是已经完成的事情:

  1. 我为现有数据库创建了一个空的 InitialCreate
  2. 我做了一些其他的脚本,因为有一些变化,那些工作正常,脚本已经创建并且 运行 在数据库上

当我想使用这些脚本并迁移另一个尚未以这种方式初始化的数据库时,就会出现问题。我不知道该怎么办。

当我尝试 运行 Update-database 时出现错误:

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
You can use the Add-Migration command to write the pending model changes to a code-based migration.

如果我执行 Add-Migration,它会再次创建一个包含所有内容的迁移,所有创建的表,就像它忽略了我的当前脚本,事实上有一个 InitialCreate 空的和其他脚本。

好的,您有 2 个数据库 - 比如说 DEV 和 PROD。在启用迁移之前,两者处于相同的状态并且具有相同的架构。这是要做的事情:

1 - 将迁移添加到您的 DEV 环境并将数据库初始化程序设置为 MigrateDatabaseToLatestVersion. Another option is to

enable-migrations
// take a snapshot of current state. -IgnoreChanges prevents recreate of existing objects.
add-migration InitialBaseline -IgnoreChanges
update-database

2 - 有几种方法可以使其他数据库保持同步:

A) 通过更改连接字符串维护并行迁移。因此,指向 PROD,然后 运行 update-database 创建 __MigrationHistory table 并应用初始空白基线。我不建议将此选项用于 PROD 数据库(见下文)。

B) 与脚本同步。许多组织不希望 EF 应用更改,而是要求 DBA 应用脚本。对于此选项,您可能希望将数据库初始化程序设置为 NULL。在这种情况下,您可以执行 update-database -Script 来生成更改。这将在初始基线之后的迁移上完成,因为它们已经同步。有关此技术的更多信息,请参阅 here

C) 使用数据库项目或 diff 工具来保持同步。

现在,当您在 DEV 中更改模型时:

add-migration Changes1
update-database

对于选项 A,更改连接字符串并重复。对于选项 B,使用 update-database -Script。对于选项 C,使用工具重新同步。

注意:"I needed to activate automatic migrations..." - 自动迁移是完全不同的事情,可能会使过程复杂化。参见 here