LoginSignup
15
14

More than 5 years have passed since last update.

WebアプリでDebugビルドとReleaseビルド時にconnectionStringsを切り替える

Posted at

Webアプリを作ってて、「Debug時とRelease時で勝手にDBの接続先が変わってくれたらなぁ・・・」と思うことはありませんかっ?

かく言う私もソウデシタ・・・。

でもこれ、簡単にできるんですよねぇ。
まず、Web.configに普通にconnectionStringsを書く。

Web.config
<configuration>
  <connectionStrings>
    <add name="OracleDB" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=ホスト名)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=サービス名))); User Id=ユーザー名; Password=パスワード" />
  </connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
</configuration>

んで、ソリューションエクスプローラを見てみると・・・なにやらWeb.configにマークがあるではありませんか?
そこにはWeb.Debug.configと、Web.Release.config・・・あやしいですね!

おもむろにWeb.Debug.configにさっきのconnectionStrings+αを書く

Web.Debug.config
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="OracleDB" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=ホスト名)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=サービス名))); User Id=ユーザー名; Password=パスワード" xdt:Transform="Replace" xdt:Locator="Match(name)"/>
  </connectionStrings>
  <system.web>
  </system.web>
</configuration>

Web.Release.configにも同様に書く。
で、+αの部分は以下の所

connectionStringsの最後
 xdt:Transform="Replace" xdt:Locator="Match(name)"

これを書いておけば、ビルド時に置換してくれるんですねぇ。
いやぁ楽になったものです。

つか、Web.Debug|Release.configのコメントに書いてあるけどな・・・。'`,、('∀`) '`,、

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14