简体   繁体   中英

EF Core - Create a migration without connection string

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM