Home > other >  Updating databases in Entity Framework for development and production environments in ASP.NET Core
Updating databases in Entity Framework for development and production environments in ASP.NET Core

Time:06-01

How do I apply EF migrations to multiple databases, referencing either a Development or Production environment as required?

TL;DR

I'm developing an ASP.NET Core MVC application using Entity Framework that references different databases for Development and Production. Both databases are hosted Azure SQL databases.

The application at the moment is running on IIS Express on my Development machine, but I will deploy Production to an Azure App Service. I'm using Entity Framework and migrations to update the database design.

I've applied this answer to use a different database connection string for either the Development or Production launch configurations, and this seems to be working. The connection strings are then stored in appsettings.Development.json or appsettings.Production.json.

When I select the DEV launch configuration, I am able to use the EF cli command dotnet ef database update in order to apply my migrations to the development database. Works fine.

However, I cannot work out how to tell Visual Studio to apply each migration to the production database when I run under the PROD launch configuration.

Running the command dotnet ef database update after changing the launch configuration continues referencing the development database, and nothing changes. I'm not surprised by this - I haven't told Visual Studio where to find the other database. But I also can't work out how to do this.

Is there a way to change the referenced database, based on the launch configuration or environment variables? Or some other convenient way?

launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:57961",
      "sslPort": 44320
    }
  },
  "profiles": {
    "IIS Express (dev)": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express (prod)": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    }
  }
}

CodePudding user response:

According to the documentation, you can specify the connection string as an extra parameter:

--connection: The connection string to the database. Defaults to the one specified in AddDbContext or OnConfiguring.

So this command will let you specify which database you are targeting:

dotnet ef database update --connection "<sql connection string>"
  • Related