Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments to IDesignTimeDbContextFactory of EF Core

How can we pass arguments to dotnet ef database update?

i want to be able to update different database with the use of arguments.

i've tried

dotnet ef database update "Accept"

dotnet ef databse update Accept

but it didn't work..

Or how I can put a switch to get different conenctionString from my configuration?

public ProjectContext CreateDbContext(string[] args)
{
    IConfigurationRoot configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    // Find a way to get different connection string 
    var connectionString = configuration.GetConnectionString(args[0]);

    var builder = new DbContextOptionsBuilder<ProjectContext >();
    builder.UseSqlServer(connectionString);

    return new ProjectContext(builder.Options);
}
like image 519
Vince Avatar asked May 27 '18 15:05

Vince


1 Answers

.NET 5 releases in a couple weeks from the time of this answer. So this is possible to change.

Answer Now

The .NET 5, and the associated EF Core 5+ NuGets support this. In Package Manager you can type:

Add-Migration YourMigrationName -Args "Space Separated Args"
Update-Database -Args "Space Separated Args"

For example, I use this:

Update-Database -Args MyConnName

In my Startup project I have a config file (Or appsettings.json) that has that connection string key, and I pull that in.

Note I said .NET Core 5. This will be have a full release in a few weeks from now. So in a few weeks this answer may be simple. But until then, you may need to install Preview versions (And NuGet PreReleases)

Answer Prior to now

There were lacking options when this question was asked, though there were options, like using dotnet ef commands with AppArgs, as discussed here. But these have changed, and are also now accessible from PM Console as discussed in the above "Now" answer.

like image 145
Suamere Avatar answered Sep 22 '22 16:09

Suamere