Search code examples
c#environment-variablesvisual-studio-2019ef-core-3.1package-manager-console

EF Core set environment not working predictably


When I go to update my database I run $env:ASPNETCORE_ENVIRONMENT="Development" first before executing the Update-Database command to set the correct environment. If I had previously deployed changes to Test for example, running this command should point me back to my Development environment and no longer be pointing at Test.

Unfortunately this only works maybe 33% of the time. Every time I run this I also run $env:ASPNETCORE_ENVIRONMENT and check that it returns back the correct environment and it does. Then I run the Update-Database command that I need and it somehow changes back to the previous environment.

Anyone have any idea on either what I am doing wrong or a way to know that I will be connected to the correct DB? This could be very bad if the wrong database is hit and data happens to get deleted or a system goes down.


Solution

  • The way that I have worked around this for the past couple of years is to have a second terminal window (I use cmder so I can use a linux based command line environment) and use dotnet commands from there. So far I haven't had any issue doing this and don't have any faith in the package manager console.

    Commands take the form of the following:

    Set current environment set ASPNETCORE_ENVIRONMENT=development

    Add new Migration: dotnet ef migrations add MyNewMigration

    Revert Migration: dotnet ef migrations remove