我在轮询服务中有一个配置文件和一个使用不同方法的轮询服务。我想要发生的是,当它在轮询服务中遇到某个方法时,我想改变配置文件中的连接字符串:
<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" />
请协助。
感谢。
答案 0 :(得分:0)
如果您确实要更改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();