3

我正在使用 C# 4.0。(Winform 应用程序)我有这样的代码:

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;具有正确的值,但它仍然没有更改连接字符串。

4

2 回答 2

3

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

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings[connStringName].ConnectionString = newValue;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
于 2013-09-17T14:21:43.533 回答
0

我认为你所需要的只是,在之后Save,一个:

ConfigurationManager.RefreshSection("connectionStrings");

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

于 2013-09-17T14:20:47.663 回答