Entity Framework Core migration - connection string

.net-core c# ef-migrations entity-framework-core


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.

11/29/2017 2:23:34 PM

Popular Answer

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>()
        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
9/15/2018 9:14:00 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