Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,i have a asp.net web application using 4.5 ,and ms sql server 2012 as backend
which has five different database with each different login credential stored in a table
I have five different connection string in web.config as
XML
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
    <add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
etc

User will enter there login credential and i want depending upon login credential user will be connected to his/her database throughout the project.

For this i have use session object like
in signup button click event
if(user=="local")
session["connectionstring"]="LocalSqlServer"
else
{
 session["connectionstring"]="MainConnStr";
}


and use this session object throughout my application like this

string strcon = ConfigurationManager.ConnectionStrings[""+session["connectionstring"]+""].ConnectionString;

SqlConnection con = new SqlConnection(strcon);
con.Open();



the above code is working for me as per to my required but i have a very big project ,
Is there any better approach to achieve My requirement or should i have to stick to the above solution.

Please someone provide me the better approach or solution to deal with this kind of scenario.
Posted
Updated 21-Oct-14 8:03am
v2

1 solution

Seems correct. Couple of suggestions.

1. You should always check for null, before reading the Session.
2. Instead of writing the connection code everywhere, declare as a property of one new class. When you require the connection string, just instantiated the class. Thus, the session checking codes will only be present inside that class constructor or a method.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900