Migrations in Entity Framework Core 2.0 - How to specify environment or pass arguments

asp.net-core c# entity-framework entity-framework-core


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?

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.

6/8/2017 8:22:50 PM

Popular Answer

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

Environment Variable for this CMD Session (Windows):


Environment Variable in your User Environment (Windows):

setx ASPNETCORE_ENVIRONMENT <Environment Name>

Also possible via GUI (Windows)

"Start" -> "Edit the system environment Variables" -> "Environment Variables" -> "New"

Environment Variable for this Shell session (Linux):

export ASPNETCORE_ENVIRONMENT=<Environment Name>

Environment Variable in you User Environment (Linux):

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()
            .AddJsonFile($"appsettings.{envName}.json", true)

        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

9/6/2017 7:51:44 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow