我正在尝试使用此代码修改连接字符串。
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 through 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);
//
var tg = entityBuilder.ProviderConnectionString;
entityBuilder.ProviderConnectionString = newValue;
//back the modified connection string to the configuration file
atr.NextAttribute.Value = entityBuilder.ToString();
}
}
}
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
return true;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Error: " + ex);
//Console.WriteLine(ex.Message);
return false;
}
}
但它只能运作一次。我在https://bhrnjica.net/2011/01/30/handling-with-connection-string-at-run-time-in-developing-the-desktop-applications/找到了它在运行时"更改实体框架的连接字符串"
我正在使用表单,我有一个组合框,其中我有一个修改字符串变量的SelectedIndexChanged,我想切换我拥有的包含不同用户数据的2个数据库。
这是我正在使用的2个连接字符串
connection = "data source=FASTEC-ATTEST\\SQLEXPRESS;initial catalog=MigrateDBFaktura3;persist security info=True;user id=Faktura;password=*******;MultipleActiveResultSets=True;App=EntityFramework";
connection = "data source=FASTEC-ATTEST\\SQLEXPRESS;initial catalog=MigrateDBFaktura5;persist security info=True;user id=Faktura;password=*******;MultipleActiveResultSets=True;App=EntityFramework";
现在我有一个运行ChangeEFConnectionString的按钮和一个清除然后使用正在使用的服务器中的用户名来伪装另一个cobobox的函数。但它只会改变一次然后我需要重新启动程序,如果我想连接到外部。