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>();
builder.UseSqlServer(@"Server=localhost;Database=db;User=sa;Password=pass;");
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?
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()
.AddUserSecrets()
.Build();
var connectionString = config.GetConnectionString("Foo");