动态更改实体连接

时间:2013-09-17 14:15:20

标签: c# entity-framework connection

我正在使用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;具有正确的值 但它仍然没有改变连接字符串。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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

ConfigurationManager.RefreshSection("connectionStrings");

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