我在运行时在web.config中创建了Connectionstring。现在,我将一些数据保存到数据库中,但仍在读取旧的Connectionstring。我该如何解决?下面是我的代码:
public string EditConnectionString(string userId, string password, string host, string dbName)
{
try
{
System.Configuration.Configuration Config = WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection conSetting = (ConnectionStringsSection)Config.GetSection("connectionStrings");
string providerName = "System.Data.EntityClient";
string conString = @"metadata=res://*/OWordpress.csdl|res://*/OWordpress.ssdl|res://*/OWordpress.msl;provider=System.Data.SqlClient;provider connection string=" + "\"data source=" + host + ";initial catalog=" + dbName + ";user id=" + userId + ";password=" + password + ";MultipleActiveResultSets=True;App=EntityFramework\"";
ConnectionStringSettings StringSettings = new ConnectionStringSettings("OWordpressContainer", conString,providerName);
conSetting.ConnectionStrings.Remove(StringSettings);
conSetting.ConnectionStrings.Add(StringSettings);
Config.Save(ConfigurationSaveMode.Modified);
return MessageFamily.Success.ToString();
}
catch(Exception ex)
{
return ex.Message.ToString();
}
}
创建了连接字符串后,我正在保存一些数据,如下所示,但它仍读取旧的连接字符串值:
public string SaveDbInfo(string userId, string password, string host, string dbName)
{
try
{
var optionEntity = new Options();
optionEntity.key = "DBInfo";
optionEntity.value = "{userId:'" + userId + "',password:'" + password + "',host:'"+host+"',dbName:'"+dbName+"'}";
objContext.Options.Add(optionEntity);
objContext.SaveChanges();
return MessageFamily.Success.ToString();
}
catch(Exception ex)
{
return ex.Message.ToString();
}
}
最佳答案
我使用EntityConnectionStringBuilder
解决了这个问题
var ecsBuilder = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["OWordpressContainer"].ToString());
var sqlCsBuilder = new SqlConnectionStringBuilder(ecsBuilder.ProviderConnectionString)
{
InitialCatalog = dbName,
UserID=userId,
DataSource=host,
Password=password
};
var providerConnectionString = sqlCsBuilder.ToString();
ecsBuilder.ProviderConnectionString = providerConnectionString;
string contextConnectionString = ecsBuilder.ToString();
using (var db = new DbContext(contextConnectionString))
{
OWordpressContainer objContext = new OWordpressContainer(contextConnectionString);
var optionEntity = new Options();
optionEntity.key = "DBInfo";
optionEntity.value = "{userId:" + userId + "',password:'" + password + "',host:'" + host + "',dbName:'" + dbName + "'}";
objContext.Options.Add(optionEntity);
objContext.SaveChanges();
}
关于c# - 在C#中以编程方式更新连接字符串后重新加载web.config,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30502764/