Pass arguments to IDesignTimeDbContextFactory of EF Core

.net-core entity-framework-core

Question

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);
}
1
4
5/27/2018 3:29:53 PM

Popular Answer

I had a similar issue recently trying to get an Asp.Net Core app to read the connection string. It turns out that you don't need the IDesignTimeDbContextFactory. Instead, just make sure that your context has a paramerless constructor, and use something like this in the startup:

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));

This should resolve to whichever connection string you have configured. If you did want to use two separate connections at the same time (which I realise you didn't want), you could do this by registering multiple DbContexts at this point; for example:

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));

services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("OtherConnection")));
1
6/29/2018 7:30:36 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow