简短版:
我需要在一个winforms应用程序(DEV,LIVE和DEMO)中循环遍历三个不同的连接字符串。我使用ConfigurationManager更新基本连接字符串。这有效。但是,我的DBContext仅尊重对连接字符串的第一次更改。其余的都被忽略了。
详细信息:
这些数据库都是使用相同的上下文构建的,代码优先。
我的App.config中有一个名为MY_DB的连接字符串。
这是主循环:
// Get the necessary Config values
string DEFAULT_DB = "MY_DB";
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection csSection = config.ConnectionStrings;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.ConnectionString = csSection.ConnectionStrings[DEFAULT_DB].ConnectionString;
string provider = csSection.ConnectionStrings[DEFAULT_DB].ProviderName;
System.Diagnostics.Debug.WriteLine(String.Format("Initial: {0}", builder["Initial Catalog"]));
// Loop through my databases
string[] catalogArray = { "live", "demo", "dev" };
foreach (string catalog in catalogArray)
{
builder["Initial Catalog"] = catalog;
config.ConnectionStrings.ConnectionStrings.Remove(DEFAULT_DB);
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(DEFAULT_DB, builder.ConnectionString, provider));
config.ConnectionStrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
// Tried both of these. Same results.
// ConfigurationManager.RefreshSection("configuration");
ConfigurationManager.RefreshSection("connectionStrings");
System.Diagnostics.Debug.WriteLine(String.Format("Processing: {0}", csSection.ConnectionStrings[DEFAULT_DB].ConnectionString));
DoDBStuff();
// Also tried this. No joy.
// System.GC.Collect();
}
这是DoDBStuff:
public void DoDBStuff()
{
using (MyContext db = new MyContext())
{
string connstr = db.Database.Connection.ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connstr);
string context = builder.InitialCatalog;
System.Diagnostics.Debug.WriteLine(String.Format("DoDBStuff is Using: {0}", context));
}
}
这是输出(已消毒):
/*
Initial: dev
Processing: Data Source=1.2.3.4;Initial Catalog=live;User ID=nope;Password=supersecure;MultipleActiveResultSets=True
DoDBStuff is Using: live
Processing: Data Source=1.2.3.4;Initial Catalog=demo;User ID=nope;Password=supersecure;MultipleActiveResultSets=True
DoDBStuff is Using: live
Processing: Data Source=1.2.3.4;Initial Catalog=dev;User ID=nope;Password=supersecure;MultipleActiveResultSets=True
DoDBStuff is Using: live
*/
所以,亲爱的Overflowers,为什么应用程序坚持只使用第一个配置'覆盖'而忽略其他配置?
顺便说一句,我很清楚我可以这样做:
MyContext db = new MyContext("CONNECTION_STRING_NAME");
我不想那样做。主要是因为我调用的很多静态方法都有自己的内部使用方法。像这样......
public static Customer ById(int id)
{
try
{
using (MyContext db = new MyContext())
{
return db.Customer.Find(id);
}
}
catch
{
return null;
}
}
有太多人无法全部覆盖它们。
帮助!