7

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.

dmoore1181
  • 1,793
  • 1
  • 25
  • 57
  • do you mean Debug and Release modes? – Nitin Sawant Aug 24 '20 at 19:22
  • No, I mean setting the environment that is going to be updated, so QA, Test, Staging, Production would be possible examples. This way the correct database is impacted. – dmoore1181 Aug 25 '20 at 12:37
  • 1
    I don't know why it happens, but it's very frustrating, don't know how many times I've accidentally updated Staging after running `$env:ASPNETCORE_ENVIRONMENT="Development"` - I basically double check every single time now with `$env:ASPNETCORE_ENVIRONMENT` because it just doesn't seem to work as it should sometimes. – jamheadart Oct 01 '21 at 13:22
  • 1
    This still happens even with VS2022! – Ziad Akiki Nov 07 '21 at 20:56

2 Answers2

0

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

dmoore1181
  • 1,793
  • 1
  • 25
  • 57
  • I just noticed some recent activity on this story and realized I hadn't picked or placed an answer. Hopefully this helps somebody even though it may not be ideal. – dmoore1181 Feb 16 '23 at 17:48
-1

Rather than exporting the variable at command line, you should set/export the variables within the database update script. So if you are running a shell script, you can export via standard export commands. If you are running perl/python, you should update the environment variables within the script. That way, you will have consistent behavior.

awadhesh pathak
  • 121
  • 1
  • 4