簡體   English   中英

在運行時更改LINQ-to-SQL連接字符串

[英]Changing LINQ-to-SQL connection string at runtime

我的應用程序廣泛使用LINQ-to-SQL,現在要求應用程序能夠在運行時切換它正在查看的數據庫 - 所以基本上我希望能夠選擇我的連接字符串我聲明它時的數據上下文。

有這么簡單的方法嗎?

只需致電:

DataContext context = new DataContext ("cxstring");

您可以使用App.config存儲連接字符串,然后使用它們填充下拉框或其他內容。 然后在LINQ2SQL數據上下文的構造函數中使用選定的Connection字符串。

App配置:

<configuration>
  <connectionStrings>
    <add key="ConString1" connectionString="ConnectionStringGoesHere"/>
    <add key="ConString2" connectionString="ConnectionStringGoesHere"/>

  </connectionStrings>

使用ConfigurationManager類訪問連接字符串。

string conString = ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;

您還可以枚舉它們或將它們設置為數據源以填充下拉框。

然后簡單地將所選字符串作為LINQ2SQL datacontext構造函數中的第一個參數傳遞。

MyModelDataContext context = new MyModelDataContext(selectedConString);

如果您的意思是通過切換應用程序正在查看的數據庫,測試數據庫和生產數據庫,只需在web.config文件中使用相同的密鑰創建兩個連接字符串,但具有不同的連接字符串並根據需要對其中一個進行注釋數據庫

<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=ProductionDB;" providerName="System.Data.SqlClient" />
<!--<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=TestDB;" providerName="System.Data.SqlClient" />-->

通過注釋和取消注釋,您可以在運行時在兩個數據庫之間切換。

選擇上下文的連接字符串,為其提供構造函數

DataContext Productioncontext = new DataContext ("MyConnectioString");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM