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.
Migrations are enabled by default in EF Core. They are managed by executing commands. If you have Visual Studio, you can use the Package Manager Console (PMC) to manage migrations. Alternatively, you can use a command line tool to execute Entity Framework CLI commands to create a migration.
Entity Framework (EF) Core, Microsoft's object-to-database mapper library for . NET Framework, brings performance improvements for data updates in version 7, Microsoft claims. The performance of SaveChanges method in EF7 is up to 74% faster than in EF6, in some scenarios.
Entity Framework automatically creates database when it doesn't exist.
Delete your Migrations folder. Create a new migration and generate a SQL script for it. In your database, delete all rows from the migrations history table. Insert a single row into the migrations history, to record that the first migration has already been applied, since your tables are already there.
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://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With