I’ve been using Entity Framework in a Net Core API I’m building recently, using the code first approach. Some way into the development, we had several environments – a Dev only environment and a Test environment, with separate databases in each. I’d made some code changes, ran the Add-Migration
command and then ran the Update-Database
command…. but my database hadn’t changed at all even though it said it had succeeded. Eventually I realised I’d changed the database in the Test environment, not the Dev environment. So I needed to find out how to make sure the correct environment was selected the next time I run the Update-Database command, therefore making sure the correct database was altered. I’ll explain how to set the environment during dotnet ef migrations in this post.
Table of contents
Set up environments in your launchSettings.json file
First of all you need to make sure your environments are configured in your .Net project – this is done in the launchsettings.json file. You need to add a profile for each environment. Here is an example:
{ "$schema": "https://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:63812", "sslPort": 44396 } }, "profiles": { "Dev": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "swagger", "applicationUrl": "https://localhost:7291;http://localhost:5291", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Dev" } }, "Test": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "applicationUrl": "", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Test" } }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Dev" } } } }
Set up an appsettings file for each environment
Now create an appsettings file for each environment so you end up with one for each, so in this case you’d have:
appsettings.json
-appsettings.dev.json
-appsettings.test.json
…. where each file contains the database connection string to the environment specific database.
Set the correct environment before updating the database
To target a specific environment, use this command, where ‘Dev’ needs to match the environment you need to target:
$env:ASPNETCORE_ENVIRONMENT='Dev'
And then you can run:
Update-Database
It will now use the correct appsettings file, which contains the correct database connection string.
Summary
You now know how to set an environment variable before doing dotnet ef migrations. More specifically I’ve provided an example of how to set the ASPNETCORE_ENVIRONMENT value so that you target the intended environment before you Add-Migration or Update-Database.