vb.netconnection-stringdefault-database

Retrieving default database connection string in code


I am working with the existing structures used by the dev team at my current company. In order to change connection strings within the application, the team creates an XML node called "defaultDatabase" (see below):

  </configSections>
<dataConfiguration defaultDatabase="Development" />
  <connectionStrings>
<add name="Development" connectionString="Data source=DVHQSQL01; Initial Catalog=db; User ID=id; Password=password"/>
  </connectionStrings>

...there will be more connection strings in the XML for different server environments (not shown here, but "Testing", "Staging", "Production", etc)

I am creating a class with different functions that use the default connection. I know one route is through ConfigurationManager as shown here:

https://social.msdn.microsoft.com/Forums/en-US/9a8c9f5a-092e-4c4a-87bb-9f35d8f55da1/get-connection-string-from-appconfig-file?forum=adodotnetdataproviders

This is great if you can change the connection string name in code, but we use the defaultDatabase node to be able to change from different environments without rebuilding.

Does anyone have experience with this methodology? How do I get the correct connection string using the defaultDatabase node?


Solution

  • Just set the default connection in the connection strings area:

    <connectionStrings>
       <add name="default" connectionString="..."/>
    </connectionStrings>
    

    If you have further connections you can add them in the same way:

    <connectionStrings>
       <add name="default" connectionString="..."/>
       <add name="special1" connectionString="..."/>
       <add name="special2" connectionString="..."/>
    </connectionStrings>