VS2008中设计.dbml文件时,如果选择“保存”“数据库连接字符串”,这些信息会存储在Propreties/Settings.settings.cs文件中。
想在发布的时候更改连接字符串,该如何做?其实,秘密都在app.config文件中.
VS2008在产生Settings.settings的同时,此文件中的信息已经存储在app.config,我们只要在修改config中对象的信息,就可以动态改变数据库连接字符串等内容。
如果要在Web项目中引用,发布的时候将dbml文件所在程序集生成的app.config文件信息拷贝到web.config文件中即可。
注意:*.dbml文件中也存在存储了连接字符串的信息,对VS2008在设计时进行支持。
更换dbml文件的连接字符串的步骤如下:设计器中选择dbml文件->属性窗口->连接,修改即可.
简单代码如下,只要仔细看,你能发现他们构成的规律
dbml的xml文件,注意 Connection 节点
<?
xml version="1.0" encoding="utf-8"
?>
<
Database
Name
="Database1"
Class
="DataClasses2DataContext"
xmlns
="http://schemas.microsoft.com/linqtosql/dbml/2007"
>
<
Connection
Mode
="AppSettings"
ConnectionString
="Data Source=server2003bak;Initial Catalog=MYTEST;User ID=sa"
SettingsObjectName
="WindowsFormsApplication1.Properties.Settings"
SettingsPropertyName
="ConnString"
Provider
="System.Data.SqlClient"
/>
<
Table
Name
="dbo.Table2"
Member
="Table2"
>
Settings.settings.cs文件内容
namespace
WindowsFormsApplication1.Properties {
[
global
::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[
global
::System.CodeDom.Compiler.GeneratedCodeAttribute(
"
Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator
"
,
"
9.0.0.0
"
)]
internal
sealed
partial
class
Settings :
global
::System.Configuration.ApplicationSettingsBase {
private
static
Settings defaultInstance
=
((Settings)(
global
::System.Configuration.ApplicationSettingsBase.Synchronized(
new
Settings())));
public
static
Settings Default {
get
{
return
defaultInstance;
}
}
[
global
::System.Configuration.ApplicationScopedSettingAttribute()]
[
global
::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[
global
::System.Configuration.SpecialSettingAttribute(
global
::System.Configuration.SpecialSetting.ConnectionString)]
[
global
::System.Configuration.DefaultSettingValueAttribute(
"
Data Source=server2003bak;Initial Catalog=MYTEST;User ID=sa;Password=123
"
)]
public
string
ConnString {
get
{
return
((
string
)(
this
[
"
ConnString
"
]));
}
}
}
}
自动生成的app.config文件
<?
xml version
=
"
1.0
"
encoding
=
"
utf-8
"
?>
<
configuration
>
<
configSections
>
</
configSections
>
<
connectionStrings
>
<
add name
=
"
WindowsFormsApplication1.Properties.Settings.ConnString
"
connectionString
=
"
Data Source=server2003bak;Initial Catalog=MYTEST;User ID=sa;Password=123
"
providerName
=
"
System.Data.SqlClient
"
/>
</
connectionStrings
>
</
configuration
>