简体   繁体   中英

Handling multiple database and their evolutions with entity framework code first

we are developing a web application (asp.net webapi 2). For the database we use the Entity Framework 6 code-first with SQL Server. The application is not multitenant so we deploy the app (on a dedicated azure web site) with a new fresh database (SQL Azure) anytime we have a new prospect or client. Everything is automated with Powershell scripts so there is no pain in creating the web app and the fresh new db. When a stable release is tagged on source control the Integration Server updates all the client environments.

The problem comes with the database. I am using the code-first migrations provided by Entity Framework but it does not look like to be appropriate for our situation. The migrations are generated by comparing with "an existing database". That would work if all databases were created at the same time and the same migrations were apply from the beginning but they are not. We have clients and prospects that were not there when the first couples of migrations were created. Moreover, we used to keep the migrations files in versioned control and we use the MigrateDatabaseToLatestVersion , they prevent to create new database see for instance this error .

What is the appropriate way to handle such situation? Maybe the migrations are not the right way to keep all database schema "equal" to the code first schema determined by the .NET assemblies. What I am looking for is something that will generate the "appropriate" migrations for each database and apply them. This procedure could be integrated with our integration server build steps.

Note: migrating our logic to a multitenant web app is not an option, our clients will reject that...

I found out a solution for this problem. I created a dedicated answer in a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM