dotnet entity framework migration: how to set connection string environment variable, with colon, on MacOS

Viewed 637

I'm using EntityFramework in .NET to handle DB migrations. For example, dotnet ef migrations list --project My.Project --context MyDbContext.

However, some of these entity framework commands require a connection string, to connect to the DB and see what's what:

    Build started...
    Build succeeded.
    Args are:
    Schema Name: myschema
    Connection string: 
    Connection string not set up. No connection string works when adding a migration (EF compares to the snapshot.cs file) but you will need a connection string to apply a migration.
    Connection string not set up in environment variable: 'ConnectionString:SchemaAdmin'. Set the connection string in the Package Manager Console first: $env:ConnectionString:SchemaAdmin='<replace with connection string>'

So I need to set up an environment variable called ConnectionString:SchemaAdmin containing the connection string for my DB.

However, this is not easy, since there is a colon in the name of the environment variable:

    $ fo:o=bar
    bash: fo:o=bar: command not found
    $ fo\:o=bar; echo $foo
    bash: fo:o=bar: command not found

How am I supposed to do this?

1 Answers

The way that I found to resolve this was to use AddJsonFile in a builder at Startup (which allows it to find the configuration stored in the appsettings.json file) and then use that to set a private _config variable

public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        _config = builder.Build();
    }

And then I could set the configuration string as follows:

var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 
Related