Connecting to multiple databases in an MVC web application

How do I connect to different databases for a .NET MVC web application written in C #?

Here, the structure of the database table remains the same. All that changes is the name of the database. So how do I manually connect to the database or use change the connection string?

The trick is to use the same code. Depending on the url, I want the data to be displayed from different databases. So Views and Controller (pretty much) share the same wrt model code.

-Datte

+2


source to share


1 answer


Here is a very simple way to do what I think you are asking for. In your web.config file, you can define two connection strings:

<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>

      

Then, in your (base) controller, you can create a method that returns the appropriate connection string based on the request, for example:



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;
    }
}

      

You could, of course, change your selection criteria for what makes the most sense.

Good luck!

+8


source







All Articles