codein codein - 1 year ago 164
C# Question

AspNet Mvc select ConnectionString automatically

I have been working on a project for sometime now which has production version running on a shared hosting environment and one on my development machine.
The issue here is that each time I want to run the application on my development machine, I will have to modify Connection String settings to point at the localDb on development machine and vice versa when I want to publish.
This became so inconvenient for me until I came up with this solutions which is working perfectly at least.
My question is this, Is this my solution professional and reliable in Aspnet environment ? Or is there a best and proven way of achieving this solution better? thank you. please see code for details.

//Created a static method in Global.asax.cs

/// <summary>
/// Returns Connection settings based on the machine. i.e, automatically select connection strings if it's development or live server
/// </summary>
/// <param name="ArrayIndex"></param>
/// <returns> string BaseConn = (connectionstring name) </returns>

public static string

Settings( int ArrayIndex)

string[] BaseConn ={ HttpContext.Current.Request.IsLocal ? System.Configuration.ConfigurationManager.ConnectionStrings[4].Name :

//Identity database connections

HttpContext.Current.Request.IsLocal ? System.Configuration.ConfigurationManager.ConnectionStrings[5].Name :

//store database connection

HttpContext.Current.Request.IsLocal ? System.Configuration.ConfigurationManager.ConnectionStrings[6].Name :
return BaseConn[ArrayIndex];

Then I called the method in DbContext class a follow

public class MyAppDb :DbContext


public MyAppDb()
: base(MvcApplication.Settings(0))
{ }

// Some entity tables here

I Did the same for the store DbContext and Identity DbContext.
Everything seems working great both on local and live machine. though I have not been able to update the databases with this solution using codefirst migration. Not an Issue at least for now.

Answer Source

You need to use Web.Release.Config.

In Web.config you will specify your own (local) connection string and on release you will use something like this (change the config according to your own sql connection).

<configuration xmlns:xdt="">
    <add name="MyContext"
         connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SalvaVidas;Server=ServerName;Database=MyDb;Trusted_Connection=True;Integrated Security=SSPI;" 

Make sure that the name property match in both. In this example it is : name="MyContext"

NOTE: Please make sure that when you are publishing, it is going as RELEASE mode.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download