刷新EntityFramework连接

时间:2014-01-30 13:29:41

标签: c# .net entity-framework

我正在改变App.config中的EntityFramework连接字符串,如下所示:

        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");

但EntityFramework继续使用旧的连接设置,直到应用程序重新启动。有没有办法强制EntityFramework从App.config获取新的连接字符串?

2 个答案:

答案 0 :(得分:0)

即使ConfigurationManager没有缓存内容(尽管Save()可能刷新缓存),EntityFramework对象也会缓存连接。在所有可能的情况下,您需要释放这些对象并重新创建它们,以便从配置管理器中提取新的连接字符串(假设缓存被刷新)或实际上手动修改DbContext对象上的连接字符串。

答案 1 :(得分:0)

我相信特拉维斯是对的。这是我以前用过的代码:

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

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