Entity Framework Core migration - connection string

Robert picture Robert · Nov 24, 2017 · Viewed 13.2k times · Source

I'm having a problem to handle the DB connection string in conjunction with migrations. I have 2 projects:

  • Domain
  • Application

The DbContext is in the Domain project, so this is the project I run migrations against. The migrations concept enforces me to implement OnConfiguring in my DbContext and therein specify the database provider, eg:

protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
    builder.UseSqlServer("<connection string>");
}

My problem is that I don't want to use a hard coded connection string, for obvious reasons, and I cannot use ConfigurationManager to read it from the config file since the config file is in the application project.

Answer

Rory MacLeod picture Rory MacLeod · Sep 15, 2018

All the examples I've seen involve either hard-coding the connection string or putting it in my ASP.NET Core application's settings files.

If you aren't using ASP.NET Core, or maybe, I don't know, don't want to have your local environment's database details committed to source control, you can try using a temporary environment variable.

First, implement IDesignTimeDbContextFactory like this (note that IDbContextFactory is now deprecated):

public class AppContextFactory: IDesignTimeDbContextFactory<AppContext>
{
    public AppContextFactory()
    {
        // A parameter-less constructor is required by the EF Core CLI tools.
    }

    public AppContext CreateDbContext(string[] args)
    {
        var connectionString = Environment.GetEnvironmentVariable("EFCORETOOLSDB");
        if (string.IsNullOrEmpty(connectionString))
            throw new InvalidOperationException("The connection string was not set " +
            "in the 'EFCORETOOLSDB' environment variable.");

         var options = new DbContextOptionsBuilder<AppContext>()
            .UseSqlServer(connectionString)
            .Options;
        return new AppContext(options);
    }
}

Then, you can include the environment variable when you call Update-Database, or any of the other EF Core tools:

$env:EFCORETOOLSDB = "Data Source=(local);Initial Catalog=ApplicationDb;Integrated Security=True"; Update-Database