4

It used to be possible to change a context's connection string, after it was created.

I can't figure out how to do that with EF Core (and SQLite). I'm registering the context in the usual way, using the ASP.NET Core builtin IoC container.

services.AddDbContext<MyContext>(options =>
  options.UseSqlite(cfg.GetConnectionString("DefaultConnection")));

I can't change the MyContext class, as it's in a separate assembly which is the responsibility of someone else. So I can't change the constructor, OnConfiguring(), etc.

So I need to re-create/init the container's current instance, using a new connection string.

Is there a way to do this?

grokky
  • 8,537
  • 20
  • 62
  • 96

1 Answers1

-2

Sure, yo can do it by ConfigurationBuilder in Startup

    var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    Configuration = builder.Build();

And then use it in your context. If ConfigurationBuilder have reloadOnChange: true will be reloaded on change

J. Doe
  • 2,651
  • 1
  • 13
  • 31
  • 6
    I assume the OP means they want to pass a different connection string at runtime, not by modifying the configuration. – CodeCaster Mar 02 '17 at 11:29
  • Does container read the config every time it creates a new context instance? Doesn't look like it as it doesn't take a lambda, only a string `options.UseSqlite(connectionString)`. Even if so, I need to change the connection string *programmatically*, so I can't edit the file every time. Is there a way to do that in code? – grokky Mar 02 '17 at 11:31
  • 1
    You can create a function what will change `appsettings.json` – J. Doe Mar 02 '17 at 11:47
  • ... which will then affect already instantiated contexts. Again, unclear whether the OP wants that. – CodeCaster Mar 02 '17 at 17:48
  • @CodeCaster I want to be able to change the connection string for new context instances. But changing the config file won't do that, I don't think so anyway. As I wrote above, the DbContext configuration doesn't take a delegate, only a string. So once it's set, it's set and cannot be changed. – grokky Mar 02 '17 at 19:00
  • Maybe this is useful http://stackoverflow.com/questions/39499470/dynamically-changing-schema-in-entity-framework-core/39631404?noredirect=1#comment66569390_39631404 – H. Herzl Mar 03 '17 at 03:10