Reputation: 4035
I have been ranging across multiple questions, tutorials and examples for something that fits this problem.
What if I don't know my connection string at the time I want to create my first initial migration? Given I am given the opportunity to set the connection string at the time of instantiating context eg:
var connection = @"Server=(localdb)\mssqllocaldb;Database=JobsLedgerDB;Trusted_Connection=True;ConnectRetryCount=0";
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlServer(connection);
using (var context = new BloggingContext(optionsBuilder.Options))
{
// do stuff
}
As described in the docs..
If you need to have a connection string to run migrations then for those situations where you don't have one (Tenant database where you get a connection string from a user account) how do you run an initial migration??
Do you create a dummy connection string to create the migration.. seems dodgy to me. I would love some input on this.
Upvotes: 11
Views: 5680
Reputation: 2986
You can implement IDesignTimeDbContextFactory
that will be used instead your host builder in the design time. UseSqlServer now has a parameterless overload.
It will look like this and has to be in the same assembly as the db context or in the startup project:
public class MyAppDbContextFactory: IDesignTimeDbContextFactory<MyAppDbContext>
{
public MyAppDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<MyAppDbContext>();
optionsBuilder.UseSqlServer();
return new MyAppDbContext(optionsBuilder.Options);
}
}
More details can be found here: https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
Upvotes: 1