覆盖连接字符串值

时间:2016-01-18 22:53:57

标签: c# connection-string overwrite

我正在尝试覆盖MVC解决方案中的一些配置文件中的某些值。我正在做这样的事情:

 config.AppSettings.Settings["Key"].Value =newValue;
 config.Save(ConfigurationSaveMode.Modified);

我的问题是,如何为ConnectionString文件做类似的事情?我正在尝试使用此代码。

 System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
    builder["InitialCatalog"] = newValue;

1 个答案:

答案 0 :(得分:1)

您可以通过多种方式实现这一目标。一种简单的方法是创建一个代码,该代码可以根据用户从下拉列表中选择并使用配置文件中的预定义ConnectionString集动态确定连接字符串。 假设您已定义以下连接字符串,

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <connectionStrings>
    <add name="Development" connectionString="data source=MyDataSource;Initial Catalog=DevDatabase;user id=sa;Pwd=devpassword;"/>
    <add name="Test" connectionString="data source=MyDataSource;Initial Catalog=TestDatabase;user id=sa;Pwd=testpassword;"/>
  </connectionStrings>
</configuration>

现在,您可以使用以下代码循环连接字符串,并根据下拉选择确定应使用哪一个

string selectedEnvironemntName = "Development"; //set from dropdown selection
var predefinedConnections = ConfigurationManager.ConnectionStrings;
SqlConnectionStringBuilder connStringBuilder = null;

foreach( ConnectionStringSettings connString in predefinedConnections)
{
    if (connString.Name == selectedEnvironemntName )
    {
        connStringBuilder = new SqlConnectionStringBuilder(connString.ConnectionString);
    }
}

//the below two lines can be anywhere in your solution as long as you can pass the connStringBuilder to SqlConnection definition
SqlConnection connection = new SqlConnection();
connection.ConnectionString = connStringBuilder.ConnectionString;

当然,有一种依赖性。您必须确保根据配置文件中的ConnectionString名称加载下拉列值。拥有此依赖关系可确保在配置文件中添加新的ConnectionString将自动导致在UI的下拉列表中显示新条目