一般情况,可以直接使用系统自动配置的连接字符串。如果要发布或者多个数据源,则
需要手工设置数据库连接。 示例如下:
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = "DBServer";
string databaseName = "databaseName";
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = "sa";
sqlBuilder.Password = "sa";
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
entityBuilder.Provider = providerName;
// Set the Metadata location.
entityBuilder.Metadata = "res://*" ; //或从.config文件中copy
//@"res://*/NBModel.csdl|
//res://*/NBModel.ssdl|
//res://*/NBModel.msl";
string str = entityBuilder.ToString();
using (NORTHWNDEntities nwt = new NORTHWNDEntities(
entityBuilder.ToString()))
{
var query = from cat in nwt.Categories
select cat;
this.GridView1.DataSource = query;
this.GridView1.DataBind();
}