【发布时间】:2016-02-02 12:55:37
【问题描述】:
在过去的几个小时里,我一直在研究这个问题,发现了许多类似的主题,但似乎都没有帮助。
我有一个使用Entity Framework 5 的C# 应用程序,并且我有一个.edmx 数据模型,在使用应用程序配置文件中的连接字符串时可以正常工作。
现在我想在运行时更改连接字符串,但它会抛出一个异常:
不支持关键字:“元数据”。
这是我的代码:
private string GetNewConnectionString(string server, string database, string username, string password)
{
var sqlBuilder = new SqlConnectionStringBuilder()
{
DataSource = server,
InitialCatalog = database,
UserID = username,
Password = password,
IntegratedSecurity = true,
MultipleActiveResultSets = true
};
var entityBuilder = new EntityConnectionStringBuilder()
{
Provider = "System.Data.SqlClient",
ProviderConnectionString = sqlBuilder.ToString(),
Metadata = "res://*/MyTestModel.MyTestModel.csdl|res://*/MyTestModel.MyTestModel.ssdl|res://*/MyTestModel.MyTestModel.msl"
};
return entityBuilder.ToString();
}
public void insertInDB()
{
var newConnectionString = GetNewConnectionString(server, database, username, password);
//newConnectionString = newConnectionString .Replace("\"", """); // doesn't help
//newConnectionString = newConnectionString .Replace("\"", "'"); // doesn't help either
using (var context = new MyTestModel.MyEntities(newConnectionString)) // it crashes here
{
}
}
元数据应该是正确的,因为我已经从应用程序配置文件中复制了它,如果我将newConnectionString 的值复制到应用程序配置并使用它,如果我用" 替换引号,它就可以正常工作.
这是newConnectionString 的值(我只是用一些虚拟凭据替换了凭据):
metadata=res:///MyTestModel.MyTestModel.csdl|res:///MyTestModel.MyTestModel.ssdl|res://*/MyTestModel.MyTestModel.msl;provider=System。 Data.SqlClient;提供者 连接字符串="数据源=myServer;初始 目录=myDatabase;集成安全性=True;用户 ID=myDbUser;Password=myDbUserPassword;MultipleActiveResultSets=True"
我看不出有什么问题,有人能发现什么吗?
【问题讨论】:
-
您使用了错误的提供程序。如果您希望该连接正常工作,请使用 System.Data.EntityClient 而不是 System.Data.SqlClient
-
另一个人也有同样的问题:stackoverflow.com/a/25041876/609176
-
@rene 我试过了,但它给出了另一个例外 -
The specified store provider cannot be found in the configuration, or is not valid. -
@DavidSpence 我看到了这篇文章,请查看我上面的评论。
-
顺便提一下,我已经安装了Entity framework 5.0。
标签: c# entity-framework entity-framework-5 connection-string