11 c# entity-framework asp.net-mvc-3
我想在运行时为我的数据库提供连接字符串.我正在使用实体框架.这就是我到目前为止所拥有的
class MyClassDBContext:DbContext
{
public MyClassDBContext(string str) : base(str)
{
this.Database.Connection.ConnectionString = str;
}
}
Run Code Online (Sandbox Code Playgroud)
要使用上面的代码,我试过了
//create connection string
EntityConnectionStringBuilder myConn = new EntityConnectionStringBuilder();
myConn.Provider = "System.Data.SqlClient";
myConn.ProviderConnectionString = "user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30";
//inject the connection string at runtime
MyClassDBContext a = new MyClassDBContext(myConn.ToString())
Run Code Online (Sandbox Code Playgroud)
上面的代码给了我一个错误,说"不支持Provider关键字".为了尝试调试此错误,我尝试了以下操作
MyClassDBContext a = new MyClassDBContext("metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30")
Run Code Online (Sandbox Code Playgroud)
现在,我收到一条错误消息"不支持元数据关键字".所以我将代码更改为
MyClassDBContext a = new MyClassDBContext("provider=System.Data.SqlClient;provider connection string=user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30")
Run Code Online (Sandbox Code Playgroud)
现在我收到一条错误,说"不支持提供商关键字".所以我再次将代码更改为
MyClassDBContext a = new MyClassDBContext("user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30")
Run Code Online (Sandbox Code Playgroud)
现在它的工作原理!我的问题是:如何在运行时指定提供程序和元数据?看起来只接受连接字符串.我正在使用Nuget的Entity 4.3.1.
谢谢
rob*_*ich 12
基于edmx文件的EF需要"提供者"和"元数据"内容.基于代码优先的EF不需要这样,只需要常规连接字符串.如果您愿意,可以使用SqlConnectionBuilder(而不是EntityConnectionStringBuilder)构建此正常连接字符串.但正如您所见,您只需指定实际的连接详细信息.EF 4.3.1的DbContext Code-first范例中不需要Provider和Metadata.
var entityConnectionStringBuilder= new EntityConnectionStringBuilder();
entityConnectionStringBuilder.Provider = "System.Data.SqlClient";
entityConnectionStringBuilder.ProviderConnectionString = <your SQL Server connection string>;
entityConnectionStringBuilder.Metadata = "res://*";
MyClassDBContext a = new MyClassDBContext(entityConnectionStringBuilder.ToString());
Run Code Online (Sandbox Code Playgroud)
EntityConnectionStringBuilder类可用于在运行时指定提供程序和元数据
例如
var entityConnectionStringBuilder = new EntityConnectionStringBuilder(); entityConnectionStringBuilder.Provider ="System.Data.SqlClient"; entityConnectionStringBuilder.Metadata ="res:// /Example.csdl|res:// /Example.ssdl|res://*/Example.msl";
有关元数据中的CSDL,SSDL和MSDL的更多信息,请参阅
| 归档时间: |
|
| 查看次数: |
26039 次 |
| 最近记录: |