ASP.NET Core Migrations

Run migrations in a specific environment

In this post, I'll show you how to create an ASP.NET Core API (.NET 5) with different environments, and create and run migrations with Entity-Framework to a specific environment to don't break the production environment and only apply when you have sure and tested the development environment.

When we develop a real application, we need to create environments. Usually, there are 3 environments: Development, Staging, and Production. 

If we have a stable production version and we need to add more features to the application, we should start adding it to the development environment, in order to don't afflict the normal behavior. 

In asp.net core we can specify each environment databases on appsettings file. In order to make this possible, we need to create one configuration file for each environment, like in the screenshot.

After that, we should insert the connection string on each file. In my case, this connection string refers to a MySQL database.

Each file, has the same connection except the name of the database, with the prefix that contains the name of the environment.

Now, we can apply migrations to a specific database.

In the Package Manager Console of Visual Studio, before the instructions "Add-Migration xxxx" and "Update-Database" we should run the following command: $env:ASPNETCORE_ENVIRONMENT='name_of_environment'.

After that, the migration will be applied to the specific database selected.

Hope you enjoyed it and learned something new!

Do you have any doubt, or did you detect an error? Contact me!