Unsure how to set C# Connection string depending on solution configuration

1.2k views Asked by At

I'm trying to figure out how to use Solution Configuration Management in Visual Studio to set a MySQL Connection string depending on what build configuration but am fairly new to this.

I've found plenty of info on the XML for the App.config file for creating connection strings, but am unclear on how to tell the different configuration modes (excuse my lack of known terminology) to use different connection strings.

EG. I want independent environments for development and production, each use a different SQL database so as to not be developing on any production database.

What I have so far in app.config:

<connectionStrings>
    <add name="Debug" connectionString="debguconnectionstring"/>
    <add name="Production" connectionString="productionconnectionstring"/>
  </connectionStrings>

It may simply be that my lack of terminology is hindering my Google-ing capability, so even if someone could point me to a guide or dupe thread that would be excellent.

Thanks!

EDIT:

Thanks all for your answers, sadly I can only mark one of them as the correct answer. +Rep for everyone, exactly what I was looking for. Thanks again!

3

There are 3 answers

0
BgrWorker On BEST ANSWER

You're looking for config transforms, (msdn article: https://msdn.microsoft.com/en-us/library/vstudio/dd465318%28v=vs.100%29.aspx) However this will only work for web project. Using this in other projects will require custom code or, as I usually do, external packages, e.g. Slow Cheetah (https://www.nuget.org/packages/SlowCheetah/) that will allow you to use transforms in any config file.

The syntax is quite simple. You define the same node on the additional configuration file and then set the attribute "xdt:Transform" with the desired mode and "xdt:Locator" with the attribute you want to match with the transform (e.g. giving it xdt:Locator="Match(name)" will transform the item with the same name attribute)

0
Bhanu Chhabra On

This is the article which shows how to build such a config:

https://mitasoft.wordpress.com/2011/09/28/multipleappconfig/

Points to remember: give same name to the connection string, only change the other details, so in code you'll be using same name but it will change depending on the Configuration (release vs debug)

PS: Sorry not enough reputation points to post as comment to question

0
Costi On

You will need three config files, like this: - app.config - app.Debug.config - app.Release.config

Also there is already a question for this here: How to select different app.config for several build configurations