I have an application written in Core 2.0, using EF Core. I'm using a pattern where:

My problem is that when doing scaffolding (create a view from a model, even one that doesn't have anything to do with EF models, or creating a controller from a model), Startup.cs/Program.cs don't seem to run so no DI.

Since there's no connection strings around, I get failures when scaffolding. If I add the connection string into a parameterless constructor on my data context class, it works. I can take it back out before I commit my code, but it seems really dangerous.

In short:

Using the DI method of adding db configuration strings (and not having them written into your application) how do you get scaffolding to work?

Edit, some code. This is what normally runs in my application, but (I think?) because DI doesn't run during scaffolding then this constructor doesn't get called.

public monosarsqlContext(IConfiguration config)
    this.m_sqlConnectioNString = config["sqlconnectionstring"];

To get scaffolding to work, I'm currently needing to copy/paste the connection string into this parameterless constructor. Again, it works, but I'm a fat-finger commit away from pushing my database connection string into a public github repo.

public monosarsqlContext()

    this.m_sqlConnectioNString = 
    Persist Security Info=False;User ID=coolguy;Password=coolpassword";

    //only here for scaffolding, do not use
    throw new NotImplementedException("DBContext only used for 
    make use of DI method.");

3/12/2018 4:04:11 PM

Popular Answer

Per my understanding, you could try to modify the OnConfiguring method under your monosarsqlContext.cs to manually retrieve the related settings when you handle scaffolding Controller as follows:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    if (!optionsBuilder.IsConfigured)
        if (string.IsNullOrEmpty(m_sqlConnectioNString))
            var configurationBuilder = new ConfigurationBuilder();
            .AddJsonFile("azurekeyvault.json", false, true)
            .AddJsonFile("appsettings.json", false, true)

            var config = configurationBuilder.Build();


            config= configurationBuilder.Build();
3/14/2018 5:09:28 AM

Related Questions


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