2014-03-19 42 views
3

我創建了適合我的生產數據庫的代碼。但我想要改變數據庫名稱的簡單方法。這是沒有進一步行動的方式,並且代碼重複。我如何做到這一點?如何在DataContext中更改數據庫名稱

我有數據庫「MyDB_1」,「MyDB_2」 - 它充滿了用於測試的數據庫副本等。

通過ODBC更改連接的方式也很好。但我怎麼能做到這一點?

DataTrackerClassesDataContext ctx = new DataTrackerClassesDataContext(); 

// !!! I cant change the property because it's readonly: 
//ctx.Connection.Database = "MyDB_1"; 
//ctx.Connection.Database = "MyDB_2"; 

Console.WriteLine(ctx.Connection.Database); 

var custQuery = 
    from m in ctx.models 
    where m.status == 1 
    select m.id; 

foreach (int id in custQuery) 
{ 
    Console.WriteLine("{0} ", id); 
} 
+0

這是LINQ到SQL,不是兩個:) btw爲什麼你使用它,但不是實體框架? – abatishchev

+0

這就是你的web.config的用途。 – Pleun

回答

5

如果你想切換數據庫一個DataContext,然後在構造函數中的一個DataContext你會輸入新的連接字符串。

你會做這樣的維護格式:

string connectionString = 
     string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True", 
         serverName, 
         dataBaseName); 

DataTrackerClassesDataContext ctx = new DataTrackerClassesDataContext(connectionString); 

而你也只需更換此基礎上的數據庫,你想使用的連接字符串。

+0

謝謝,這是我需要的! –

+0

不客氣! – Taugenichts

+0

而不是硬編碼 - 將其移動到web.config ... – Pleun