2009-10-27 137 views
2

如何連接到用C#編寫的.NET MVC Web應用程序的不同數據庫?連接到MVC Web應用程序中的多個數據庫

這裏數據庫表的結構保持不變。所有更改都是數據庫名稱。那麼如何手動連接到數據庫或使用修改連接字符串?

訣竅是使用相同的代碼。根據我希望從不同數據庫顯示數據的URL。所以視圖和控制器(幾乎)有單個代碼w.r.t.該模型。

-Datte

+1

你如何連接到數據庫? ADO.NET? LINQ to SQL?實體框架? NHibernate的?還有別的嗎? – jrista 2009-10-27 05:40:50

+0

是的,我正在使用實體框架... – dattebayo 2009-10-27 06:11:16

回答

8

下面是一個非常簡單的方法來做我認爲你問的東西。在你的web.config文件,你可以定義你的兩個連接字符串:

<connectionStrings> 
    <add name="DevelopmentDB" providerName="System.Data.SqlClient" 
     connectionString="Data Source=sql-dev.example.com;Initial Catalog=MyDB;User Id=MyUser;Password=MyPassword" /> 
    <add name="ProductionDB" providerName="System.Data.SqlClient" 
     connectionString="Data Source=sql-prod.example.com;Initial Catalog=MyDB;User Id=MyUser;Password=MyPassword" /> 
</connectionStrings> 

然後,在你(基地)控制器,你可以創建一個返回基於此請求的連接字符串,如方法:

internal string ConnectionString 
{ 
    get 
    { 
     return getConnectionStringByServerName(this.HttpContext.Request.ServerVariables["SERVER_NAME"]); 
    } 
} 

internal string getConnectionStringByServerName(string serverName) 
{ 
    if (serverName.Equals("localhost")) 
    { 
     return WebConfigurationManager.ConnectionStrings["DevelopmentDB"].ConnectionString; 
    } 
    else 
    { 
     return WebConfigurationManager.ConnectionStrings["ProductionDB"].ConnectionString; 
    } 
} 

你當然可以改變最有意義的選擇標準。

祝你好運!

相關問題