简体   繁体   English

VS2010中每个发布配置文件的不同连接字符串

[英]Different connection string for each publish profile in VS2010

Is it possible to change connection string (or just server host) relying on selected web publish profile? 是否可以根据所选的Web发布配置文件更改连接字符串(或仅服务器主机)? Maybe using Web.config transform or someway else? 也许使用Web.config转换或其他方式?

I mean for profile "Test" change connection string "MyConnString" (in published Web.config) to "Data Source='example.com,14333;..." and for profile "Production" - to "Data Source=./SQLExpress;..." 我的意思是对于配置文件“测试”将连接字符串“MyConnString”(在已发布的Web.config中)更改为"Data Source='example.com,14333;..." ,对于配置文件“生产” - 更改为"Data Source=./SQLExpress;..." "Data Source='example.com,14333;..." "Data Source=./SQLExpress;..."

This is exactly what web config transforms were created for. 这正是创建Web配置转换的原因。 The link you provided in your post has a walkthrough of doing this specifically for connection strings. 您在帖子中提供的链接有一个专门针对连接字符串执行此操作的演练。

To start with the transforms, right-click your web.config file in the project explorer and choose "Add Config Transforms". 要从转换开始,请右键单击项目资源管理器中的web.config文件,然后选择“添加配置转换”。 Assuming that you have ConfigA and ConfigB in your solution configuration, there will be two new files added, Web.ConfigA.config and Web.ConfigB.config. 假设您的解决方案配置中有ConfigA和ConfigB,则会添加两个新文件:Web.ConfigA.config和Web.ConfigB.config。

If you open these new files, they'll be pretty empty except for a bunch of comments. 如果你打开这些新文件,除了一堆评论之外,它们都是空的。 They actually contain a connection string example in them that you can use though - it looks like this: 它们实际上包含一个连接字符串示例,您可以使用它们 - 它看起来像这样:

<connectionStrings>
  <add name="MyDB" 
    connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" 
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>

Uncomment this section, and change the "name" property to the name of the connection string in the base web.config file. 取消注释此部分,并将“name”属性更改为基本web.config文件中的连接字符串的名称。 Set the "connectionString" property to the actual value that you want to use for ConfigA. 将“connectionString”属性设置为要用于ConfigA的实际值。 So, like this: 所以,像这样:

<connectionStrings>
  <add name="myConnectionString" 
    connectionString="Data Source=ConfigASqlServer;Initial Catalog=ConfigADatabase;Integrated Security=True" 
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>

Repeat the process for the Web.ConfigB.config file, with the desired connection string for ConfigB. 对Web.ConfigB.config文件重复此过程,其中包含ConfigB的所需连接字符串。

Now when you use the Publish command in visual studio, it will automatically transform the base web.config file, and set the "connectionString" attribute to whatever configuration you're in when you publish. 现在,当您在visual studio中使用“发布”命令时,它将自动转换基本web.config文件,并将“connectionString”属性设置为您发布时所处的任何配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM