我正在使用此代码通过网络连接到我的数据库:
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = "VENUS-PC";
string databaseName = "Cheque";
// 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 = true;
sqlBuilder.UserID = "sa";
sqlBuilder.Password = "123";
sqlBuilder.MultipleActiveResultSets = true;
// 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;
// Set the Metadata location.
entityBuilder.Metadata = @"res://*/Cheque.csdl|
res://*/Cheque.ssdl|
res://*/Cheque.msl";
//Console.WriteLine(entityBuilder.ToString());
System.Windows.Forms.MessageBox.Show(entityBuilder.ToString());
using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
//Console.WriteLine("Just testing the connection.");
System.Windows.Forms.MessageBox.Show("Connection is Ok");
conn.Close();
}
但抛出此异常:底层提供程序在open.Login失败,用户'sa'失败。 我在Sql Server Managment Studio中测试用户名,密码,服务器名称和数据库名称,它正在运行。 我该如何修复我的代码?
答案 0 :(得分:1)
public static string GetConStrSQL()
{
string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = "res://*",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog = "Name Of The Database",
DataSource = @"ServerNameHere\SQLEXPRESS",
IntegratedSecurity = false,
UserID = "sa",
Password = "your_password_here",
}.ConnectionString
}.ConnectionString;
return connectionString;
}
并在创建上下文中:
YouEFContext ctx = new YouEFContext(GetConStrSQL());