我有一个配置文件和一个在轮询服务中使用不同方法的轮询服务。我想要发生的是,当它在轮询服务中遇到某种方法时,我想改变配置文件中的连接字符串:
<add name="Entity" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=dev;Initial Catalog=DB;Persist Security Info=True;User ID=a;Password=asdf;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
:
<add name="Entity" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=dev_Test;Initial Catalog=DB_Test;Persist Security Info=True;User ID=a;Password=asdf;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
请协助。
谢谢。
如果你真的想修改app.config文件,你可以这样做:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["Entity"].ConnectionString = YourNewConnectionString;
config.Save();
如果您只需要更改数据源是内部连接字符串,并且您不想解析实体连接字符串,则可以使用连接字符串生成器,如下所示:
var entityBuilder = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["Entity"].ConnectionString);
var sqlBuilder = new SqlConnectionStringBuilder(entityBuilder.ProviderConnectionString);
sqlBuilder.DataSource = "dev_Test";
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
var connectionString = entityBuilder.ToString();