动态更改实体连接

本文关键字:连接 实体 动态 | 更新日期: 2023-09-27 18:31:42

我正在使用C# 4.0。(赢形应用)我有这样的代码:

private bool ChangeEFConnectionString(string connStringName, string newValue)
{
    try
    {
        //CreateXDocument and load configuration file
        XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        //Find all connection strings
        var query1 = from p in doc.Descendants("connectionStrings").Descendants()
                     select p;
        //Go throught each connection string elements find atribute specified by argument and replace its value with newVAlue  
        foreach (var child in query1)
        {
            foreach (var atr in child.Attributes())
            {
                if (atr.Name.LocalName == "name" && atr.Value == connStringName)
                    if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
                    {
                        // Create the EF connection string from existing 
                        EntityConnectionStringBuilder entityBuilder =
                            new EntityConnectionStringBuilder(atr.NextAttribute.Value);
                        //change hte provide conn string
                        entityBuilder.ProviderConnectionString = newValue;
                        //back the full connection string to the configuration fiel
                        atr.NextAttribute.Value = entityBuilder.ToString();
                    }
            }
        }
        doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return false;
    }
}
它工作

得很好,但不知何故它不再工作了。

当我调试它时:entityBuilder.ProviderConnectionString = newValue;具有正确的值但它仍然没有更改连接字符串。

动态更改实体连接

使用 ConfigurationManager 读取和更新连接字符串:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings[connStringName].ConnectionString = newValue;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

我认为您所需要的只是,在Save之后,a:

ConfigurationManager.RefreshSection("connectionStrings");

是否考虑过为 EF 指定整个连接字符串而不是名称?这将使您不必在运行时修改名称的含义。