Home > Net >  EFCore codefirst migrations and the aspnetcore_environment
EFCore codefirst migrations and the aspnetcore_environment

Time:04-01

I've been using workarounds for a while for this issue, but figured I'd ask online and see if anyone has any hints or alternate methods for what I'm trying to achieve.

I have a very basic core 3.1 MVC setup that has setting files like this:

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

appsettings.Development.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

appsettings.Local.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=new-test-site;Trusted_Connection=True;"
  }
}

and in the launchsettings.json I have a couple of profiles setup like so:

 "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "new_test_site_local": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Local"
      }
    },
    "new_test_site_dev": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }

So in my mind, when I use the PMC to set $aspnetcore_environment="Local" that should allow my project to run with the appsettings.Local.json (e.g. the connection string) values taking precedence.

But it doesn't seem to do that? I can only get it to work if I copy-paste that "local" connection string into the dev or "normal" appsettings.

How can I run commands like add-migration and update-database with my local settings as the target?!

CodePudding user response:

Use the PowerShell syntax for setting environment variables:

$env:aspnetcore_environment="Local"
  • Related