user3223738
user3223738

Reputation: 447

Refresh EntityFramework connection

I'm changing EntityFramework connection string in App.config like this:

        var connectionString = new SqlConnectionStringBuilder(entityConnectionString.ProviderConnectionString);

        connectionString.UserID = dbUser;
        connectionString.Password = dbPass;
        connectionString.InitialCatalog = dbCatalog;
        connectionString.DataSource = dbServer;

        entityConnectionString.ProviderConnectionString = connectionString.ToString();

        cString.ConnectionString = entityConnectionString.ToString();

        conf.Save(ConfigurationSaveMode.Full);
        ConfigurationManager.RefreshSection("connectionStrings");

But EntityFramework continues to use an old connection settings until application restart. Is there any way to force EntityFramework to get new connection string from App.config?

Upvotes: 2

Views: 1969

Answers (2)

JRP
JRP

Reputation: 191

I believe Travis is right. Here is code I've used to do this:

public void RefreshContext(string myConnectionString)
{
  DisposeContext();
  Context = new MyContext(myConnectionString);
}

public void DisposeContext()
{
  if (Context == null)
    return;
  Context.Dispose();
}

Upvotes: 2

Travis
Travis

Reputation: 10547

Even if ConfigurationManager didn't cache stuff (though Save() might refresh the cache) the EntityFramework objects will cache the connection. In all likelyhood you need to release those objects and recreate them so it pulls the new connection string from configuration manager (assuming the cache gets refreshed) or actually modify the connection string on your DbContext object manually.

Upvotes: 1

Related Questions