views:

85

answers:

4

Hello,

I am developing an ASP .NET application on my PC and deploying it on a host.

The application uses a Microsoft SQL DB, I have two databases one local and one on a server.

How should the application be configured so it could connect to both DBs without any code changes? (the 2 databases have identical names and structure)

Thanks

+3  A: 

Store the connection string in web.config:

<configuration>
    <connectionStrings>
        <add name="Name" connectionString="..." />
    </connectionStrings>
</configuration>

Then in your code:

string connStr = ConfigurationManager.ConnectionStrings["Name"].ConnectionString;
David Brown
The joys of config files.
Woot4Moo
I used to hate them when switching between development and production. But .NET 4's .config transformations are pretty darn cool!
David Brown
joy indeed, thanks
Ws
A: 

and a nice website which specifies the connection string for most DBs

ram
+1  A: 

If you need to store all of them in one config file, you can also do some indirection like this:

string name = ConfigurationManager.AppSettings["DB"]
string connStr = ConfigurationManager.ConnectionStrings[name].ConnectionString;

<configuration>
 <appSettings>
  <add key="DB" name="Prod" />
 </appSettings>    
 <connectionStrings>        
   <add name="Prod" connectionString="..." />    
   <add name="Test" connectionString="..." />    
   <add name="Dev" connectionString="..." />    
 </connectionStrings>
</configuration>

It comes down to who can edit config in produciton and how you're allowed to deploy software. Sometimes this is a viable solution with the actual option to use being specified somewhere else altogether.

No Refunds No Returns
+1  A: 

The problem with using the web.config is that you have to change it when you deploy.

I have a post arguing for machine.config here.

For places where you can't edit the machine.config I show a way to have it in a config file that is not under your web site's directory here.

JBrooks