首先使用 entity framework 代码处理多个数据库及其演变

Handling multiple database and their evolutions with entity framework code first

我们正在开发 Web 应用程序 (asp.net webapi 2)。对于数据库,我们使用 Entity Framework 6 代码优先和 SQL 服务器。该应用程序不是多租户的,因此只要我们有新的潜在客户或客户,我们就会使用新的数据库 (SQL Azure) 部署该应用程序(在专用的 Azure 网站上)。一切都通过 Powershell 脚本实现自动化,因此创建 Web 应用程序和全新的数据库时没有任何痛苦。当在源代码控制上标记稳定版本时,集成服务器会更新所有客户端环境。

数据库有问题。我正在使用 Entity Framework 提供的代码优先迁移,但它看起来不适合我们的情况。迁移是通过与 "an existing database" 比较生成的。如果同时创建所有数据库并且从一开始就应用相同的迁移但事实并非如此,那将是可行的。在创建第一批迁移时,我们拥有不存在的客户和潜在客户。此外,我们过去常常将迁移文件保存在版本控制中,我们使用 MigrateDatabaseToLatestVersion,它们阻止创建新数据库 see for instance this error

处理这种情况的适当方法是什么?也许迁移不是将所有数据库架构 "equal" 保留为 .NET 程序集确定的代码优先架构的正确方法。我正在寻找的是将为每个数据库生成 "appropriate" 迁移并应用它们的东西。此过程可以与我们的集成服务器构建步骤集成。

注意:将我们的逻辑迁移到多租户 Web 应用程序不是一种选择,我们的客户会拒绝...

我找到了解决这个问题的方法。我在 blog post.

中创建了一个专门的答案

TLDR; Determine a “stable production schema”: which is the database schema corresponding to the web app code for a stable branch/tag in your source control. Avoid the so-called AutomaticMigration and always create new code based migration using Add-Migration with respect to an empty database that have been updated to the “stable production schema” after applying all existing migrations. Do not use Update-Database command to update your database in production, let the framework do it for you at startup using the MigrateDatabaseToLatestVersion initializer. Then, when you release a new environment starts the application with an empty database. You will also have to take care of version control when working with feature branches.