Use settings.json on a Net Core Class Library with EF Core migrations dotnet-cli entity-framework-core


On a NET Core 2.1 Class Library I have a Entity Framework Core 2.1 DbContext:

public class AppContext : IdentityDbContext<User, Role, Int32> {

  public AppContext(DbContextOptions options) : base(options) { }


To run migrations on the Class Library I needed to add the following:

public class ContextFactory : IDesignTimeDbContextFactory<Context> {

  public Context CreateDbContext(String[] args) {

    DbContextOptionsBuilder builder = new DbContextOptionsBuilder<Context>();


    return new Context(builder.Options);



With this I am able to run, on the class library commands like:

dotnet ef migrations add "InitialCommit"
dotnet ef database update

But how to move the connection string to a settings.json file in the Class Library?

11/8/2018 12:38:20 PM

Accepted Answer

IDesignTimeDbContextFactory, as its name implies, is strictly for development. There is generally no need to externalize the connection string, because it should be pretty static, even in a team environment. That said, if anything, you should store it in user secrets, because again, this is only for development. Using user secrets keeps the connection string out of your source control, so developers on your team don't step on each other's toes with each other's connection strings.

var config = new ConfigurationBuilder()

var connectionString = config.GetConnectionString("Foo");
11/8/2018 2:02:25 PM

Popular Answer

The IDesignTimeDbContextFactory<> implementation is run via the EF utility process. This is a regular console application where you can use Console.Write() and Console.Read() to interact with the user performing migrations and updates. This allows you to prompt the user to enter their connection string at update-time.

public class Builder : IDesignTimeDbContextFactory<AppContext>
    public AppContext CreateDbContext(string[] args)
        Console.Write("Enter your connection string: ");
        var conStr = Console.ReadLine();

        var options = new DbContextOptionsBuilder<AppContext>().UseSqlServer(conStr).Options;

        return new AppContext(options);

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