Change Connection String & Reload App.Config at Run Time

c# - Entity Framework ConnectionString won't update after changing App.Config in runtime

Entity Framework caches connection string, there isn't a method to force a refresh.

From this article: connection string given in DbContext constructor isn't cached then you can use this as workaround:

public class MyContext : DbContext {
public MyContext()
: base(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString)
{
}
}

Save and reload app.config(applicationSettings) at runtime

You need to make a call to ConfigurationManager.RefreshSection in order to have the values re-read from disk.

Can you change the ConnectionString configuration value at runtime?

Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); 
myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text;
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text;
myConfiguration.Save();

Ref: http://www.beansoftware.com/ASP.NET-Tutorials/Modify-Web.Config-Run-Time.aspx



Related Topics



Leave a reply



Submit