Wednesday, 1 October 2014

Overriding ConnectionString in Machine.config with web.config ConnectionString.


Overriding ConnectionString in Machine.config with web.config connectionstring.


If I have following connectionstring in my machine.config  (Machine level value)
<connectionStrings>
                 <add name="TestConfigConnection" connectionString="DATA SOURCE=machineCon;PERSIST SECURITY INFO=True;USER ID=usr;PASSWORD=pwd" />
 </connectionStrings>

Now for specific web application I want a different connection string value then we need to override the value in machine.config.
So we  need to add the required connectionstring value in web.config
<connectionStrings>
                 <add name="TestConfigConnection" connectionString="DATA SOURCE=webCon;PERSIST SECURITY INFO=True;USER ID=usr;PASSWORD=pwd" />
 </connectionStrings>


But with this, it will give an error in browser that
Parser Error Message: The entry 'TestConfigConnection' has already been added.

Means when you already have this key connectionstring in machine.config then why are you storing this value again in web.config file.

To overcome this error we need to remove the key in web.config and then need to add it again. So my Web.Config file will have following entry

<connectionStrings>
                 <remove name="TestConfigConnection"/>
<add name="TestConfigConnection" connectionString="DATA SOURCE=webCon;PERSIST SECURITY INFO=True;USER ID=usr;PASSWORD=pwd" />
 </connectionStrings>


This will work J