C# 动态建立实体连接

C# 动态建立实体连接,c#,entity-framework,C#,Entity Framework,我正在使用这样的代码,但我得到一个例外:“基础提供程序在打开时失败。”这可能是什么原因?我已经在app.config文件中对连接字符串进行了注释 SqlConnectionStringBuilder sqlConnection = new SqlConnectionStringBuilder(); sqlConnection.DataSource = dataSource; sqlConnection.InitialCatalog = initialCatalog; sqlConnection

我正在使用这样的代码,但我得到一个例外:“基础提供程序在打开时失败。”这可能是什么原因?我已经在
app.config
文件中对连接字符串进行了注释

SqlConnectionStringBuilder sqlConnection = new SqlConnectionStringBuilder();

sqlConnection.DataSource = dataSource;
sqlConnection.InitialCatalog = initialCatalog;
sqlConnection.IntegratedSecurity = true;

EntityConnectionStringBuilder entityConnection = new EntityConnectionStringBuilder();
entityConnection.Provider = "System.Data.SqlClient";
entityConnection.Metadata = "res://*/Restaurant.csdl|res://*/Restaurant.ssdl|res://*/Restaurant.msl";
entityConnection.ProviderConnectionString = sqlConnection.ToString();

using (EntityConnection conn = new EntityConnection(entityConnection.ToString()))
{
    conn.Open();
    MessageBox.Show("Just testing the connection.");
    conn.Close();
}

请发布InnerException。重复?请发布“entityConnection.ToString()”的值。此异常表示应用程序无法连接到数据库。可能的原因可能是:您的
sqlConnection
配置无效,或者您的数据库不接受远程连接(如果它不在您的计算机上),或者您没有访问数据库的权限。感谢您的回复。值为{metadata=res://*/Restaurant.csdl|res://*/Restaurant.ssdl | res://*/Restaurant.msl;provider=System.Data.SqlClient;provider connection string=“Data Source=KARKI/SQLEXPRESS;Initial Catalog=Restaurant;Integrated Security=True”}