Home > DeveloperSection > Forums > How to Set database connection string at run time?
Allen Scott

Total Post:36

Points:254
Posted on    November-21-2014 12:39 AM

 ASP.Net C#  ADO.Net  SQL Server 
Ratings:


 1 Reply(s)
 630  View(s)
Rate this:

I am working on a MVC 4 web site. It should allow the user to select which database to be connected with depending on user selection from the View. All the databases have the same table structure and schema etc.

I have a database ConnectionString defined in the Web.config file that allows for connection to the first database.

<connectionStrings>

    <add name="DBConnectionString" connectionString="Data Source=DATABSE_SERVER;Initial Catalog=DATABASE_NAME;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD" providerName="System.Data.SqlClient" />

</connectionStrings>

I also used Linq DataContext to initialize connection to the database. Table mappings were all automatically generated by Linq to SQL in MVC 4.

public NEMP_DataDataContext() :

            base(global::System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString, mappingSource)

{

    OnCreated();

}

What is the best way to achieve this?



marcel ethan
marcel ethan

Total Post:105

Points:735
Posted on    November-21-2014 10:26 PM

In LINQ to SQL, you just create the Context with the connection string:

DataContext myContext = new DataContext(customConnectionString);

You don't need to worry about closing them or anything. SQL Server is handling all that for you. So you simply adjust the connection string slightly (Database Name) and create a new context based on whatever variable in every page you need to use the Context.


Don't want to miss updates? Please click the below button!

Follow MindStick