实体框架运行时连接字符串

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.

  • EF连接字符串具有`Provider ="System.Data.Entity"`和`ConnectionString ="res://big.csdl | res://ball.ssdl | res://mud.msl; provider connection string =&quot ; ......"`.常规连接字符串具有`Provider ="System.Data.Client"`(或Oracle或MySql)和`ConnectionString ="详细信息以连接到它"`.这两个参数通常位于app.config或web.config中,但您选择动态制作它们.在EF Code First中,您将采用第二条路径.在EDMX中,您必须在第一个路径的"提供者连接字符串"中嵌入第二个路径的详细信息.这很难看. (4认同)

Dav*_*and 9

HatSoft的答案为基础:

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)


Hat*_*oft 7

EntityConnectionStringBuilder类可用于在运行时指定提供程序和元数据

例如

var entityConnectionStringBuilder = new EntityConnectionStringBuilder(); entityConnectionStringBuilder.Provider ="System.Data.SqlClient"; entityConnectionStringBuilder.Metadata ="res:// /Example.csdl|res:// /Example.ssdl|res://*/Example.msl";

有关元数据中的CSDL,SSDL和MSDL的更多信息,请参阅