Entity Framework not using updated connection string

c# database-connection entity-framework-6 multithreading

Accepted Answer

The ConfigurationManager.RefreshSection method's documentation does state (emphasis added):

Refreshes the named section so the next time that it is retrieved it will be re-read from disk.

The issue is that the ConfigurationManager.ConnectionStrings is never updated since EF6 caches it in an internal class static property.

Sadly, there isn't a "official" method to update it. Use at your own risk since the following is a reflection-based brute force hack:

static readonly Type EF6AppConfigType = typeof(DbContext).Assembly.GetType("System.Data.Entity.Internal.AppConfig");

static readonly PropertyInfo EF6DefaultAppConfig = EF6AppConfigType.GetProperty("DefaultInstance", BindingFlags.Public | BindingFlags.Static);

static readonly FieldInfo EF6ConnectionStrings = EF6AppConfigType.GetField("_connectionStrings", BindingFlags.NonPublic | BindingFlags.Instance);

static void RefreshEF6ConnectionStrings()
{
    EF6ConnectionStrings.SetValue(
        EF6DefaultAppConfig.GetValue(null),
        ConfigurationManager.ConnectionStrings
    );
}

After saving the adjustments, simply dial:

config.Save();
RefreshEF6ConnectionStrings();
2
7/27/2018 7:47:18 PM


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