How to separate between debug and release for connections etc in mvc4

青春壹個敷衍的年華 提交于 2019-12-06 09:33:56

I would strongly recommend not hardcoding your connection strings into your code. Please consider pointing your code to a web.config transform. You can add the connection string there and depending on the version of code the proper transform can be applied so that you simply need to use the following code once in your app to cover all environments.

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString

Inside of the debug version you could have something similar to

<configuration xmlns:xdt="...">
    <connectionStrings>
      <add name="MyConnectionString" connectionString="debugstring"
         providerName="debugprovider" />
     </connectionStrings>
</configuration>

Inside your release version you can tell the transform to replace your old string as so

<configuration xmlns:xdt="...">
    <connectionStrings>
      <add name="MyConnectionString" connectionString="newstring"
         providerName="newprovider"
         xdt:Transform="Replace" />
     </connectionStrings>
</configuration>

for more reference check out http://msdn.microsoft.com/en-us/library/dd465326.aspx

The selected answer will not work if you have more than one connection string. in the release config add below tags for all your connectionstrings

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"

This is what I have in my Web configuration files

in Web.Debug.Config

<add name="MyConnectionString" 
    connectionString="Data Source=dev;Initial Catalog=DevDB;Integrated Security=True;
    providerName="System.Data.SqlClient"/>

and in Web.Release.Config

<add name="MyConnectionString" 
    connectionString="Data Source=LIVESERVER;Initial Catalog=DB98;Integrated Security=True;
    providerName="System.Data.SqlClient" 
    xdt:Transform="SetAttributes" 
    xdt:Locator="Match(name)"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!