I'm playing with EF Core 2.0 and have 3 env in my app: dev, staging and prod. Now I want to apply db schema to specific database. However I faced with a problem. When I executing dotnet ef database drop (update)
for example, it's trying to get production env by default.
How could I specify what environment should be used? My DbContextFactory looks like that:
public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
public MyDbContext Create(string[] args) => //how to pass something to this args?
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build().Services.GetRequiredService<MyDbContext>();
}
it was something like:
dotnet ef database drop -e development
in version 1.1
, but this was removed from version 2.0
.
set ASPNETCORE_ENVIRONMENT=development
dotnet ef database drop
also seems not working.
What I gathered from here is that the -e MyCustomEnvironment
is not available in the EF Core Design Tools for Core 2.x
To set Environment Variables I discovered you have the following choices depending on your usecase
set ASPNETCORE_ENVIRONMENT <Environment Name>
setx ASPNETCORE_ENVIRONMENT <Environment Name>
"Start" -> "Edit the system environment Variables" -> "Environment Variables" -> "New"
export ASPNETCORE_ENVIRONMENT=<Environment Name>
cd ~
echo 'export ASPNETCORE_ENVIRONMENT=<Environment Name>' >> .bashrc
This will actually export the Variable everytime .bashrc is executed. I'm not sure if this is the way to go on Linux but it worked for me.
Also in my case I didn't want the StartUp code to run since I feel like for a DesignTime action its not neccessary to register all the Services etc of my Application. This could be done like so:
var basePath = AppDomain.CurrentDomain.BaseDirectory;
var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{envName}.json", true)
.AddEnvironmentVariables();
var config = builder.Build();
var customOptions = config.GetSection("database").Get<DatabaseOptions>();
Also if you have more complex szenarios you now might want to create some small batch or shell skripts