The other answers here were helpful, but I wanted to expand on exactly what I did for others that come across this.
The first thing you'll want to do is to go into your launch settings.json and add something like this:
{
"profiles": {
"DataMigration (Local)": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Local"
}
},
"DataMigration (Dev)": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Dev"
}
}
}
}
This will give you access to an environment variable depending on which profile you launch your project with (note the configuration manager has no impact here).
Then you can create different appsetting.json files. For example, I made an appsettings.Local.json
and a appsettings.Dev.json
file.
appsettings.Local.json
{
"db": "connectionstringhere"
}
and
appsettings.Dev.json
{
"db": "connectionstringhere"
}
Now, you can then access the environment variable that you run your app with like so:
static void Main(string[] args)
{
var myEnv = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile($"appsettings.{myEnv}.json", false)
.Build();
var dbconnection = config["db"];
}
To take it a step further, instead of doing it here, I made by db context flexible like so:
public class ShoppingDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var myEnv = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if(myEnv != null)
{
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile($"appsettings.{myEnv}.json", false)
.Build();
var sl = config[$"db"];
optionsBuilder.UseSqlServer(sl);
}
else
{
// we are testing and want local for sure
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile($"appsettings.Local.json", false)
.Build();
var sl = config[$"db"];
optionsBuilder.UseSqlServer(sl);
}
}
public DbSet<MyTable> MyTables { get; set; }
}