[英]Writing and Retrieving connection string for Entity Framework
最初,我是在登錄時為項目構建並將連接字符串保存在app.config文件中的。 但是,我們內部的一位用戶遇到了這樣的事件,即保存在數據庫中的數據莫名其妙地不在那兒。 盡管注銷並再次登錄可以緩解該問題。
從那時起,我意識到,由於我們所有人都使用共享驅動器上存儲的程序的共享副本以及桌面上的快捷方式,因此,每當有人登錄時,它都會更改連接字符串,該字符串也被所有人共享。
因此,我一直試圖將其保存到%appData%文件夾下的本地用戶文件中。
這就是我以前的經驗,如果我們使用應用程序的本地副本,它將可以正常工作。
public class UpdateConfig
{
public static void UpdateConfigConnString(string s)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["MyDB"].ConnectionString = s;
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
}
我試圖將ConfigurationUserLevel
更改為None
,但這給了我一個關於無法更改鎖定項目的錯誤。
根據此MSDN文檔,這是我現在的位置:
public class UpdateConfig
{
public static void UpdateConfigConnString(string s)
{
string sectionName = "MyDB";
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = config.FilePath;
var currentSection = (ConnectionStringsSection)config.GetSection(sectionName);
if (currentSection == null)
{
currentSection = new ConnectionStringsSection();
currentSection.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToRoamingUser;
currentSection.SectionInformation.AllowOverride = true;
currentSection.ConnectionStrings.Add(new ConnectionStringSettings("MyDB", s));
}
config.Save(ConfigurationSaveMode.Modified);
Debug.WriteLine(config.FilePath);
ConfigurationManager.RefreshSection("connectionStrings");
}
}
運行它並不能告訴我很多,除了不會出錯。 但是,當我嘗試查找Debug.WriteLine
打印出的文件時,Windows找不到它。 此外,我不確定如何確保我的實體框架項目知道在哪里查找連接字符串。
任何見識將不勝感激。 或者,如果我要解決所有這些錯誤,那么我願意接受更好的建議,謝謝。
如果需要根據用戶輸入動態更改連接字符串,則上述方法均無效。 由於無法從共享位置運行exe文件,因此無法在每個用戶應用程序數據中保存配置文件。 另外,在這種情況下更新exe文件本身是非常不好的做法。 因此,最好不要更新配置文件並考慮其他方法。
我認為您應該做的是構建將自定義連接字符串傳遞給Entity Framework的路徑。 您可以輕松地創建一個構造函數重載,該重載將接受自定義連接字符串並將其傳遞。 由於您已經有了自定義連接字符串,因此只需添加管道代碼來傳遞它即可。 請參閱以下帖子,了解如何操作:
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.