实体框架运行时的连接字符串 [英] Entity Framework runtime connection string

查看:135
本文介绍了实体框架运行时的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提供连接字符串我在运行时的数据库。我使用的是实体框架。这是我迄今为止

I'd like to supply the connection string for my database at runtime. I am using the Entity Framework. This is what I have so far

class MyClassDBContext:DbContext
{
  public MyClassDBContext(string str) : base(str)
  {
    this.Database.Connection.ConnectionString = str;
  }
}

要使用上述code,我试过

To use the above code, I tried

//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())

以上code给了我一个错误说不支持的提供关键词。
要尝试调试这个错误,我尝试以下

The above code gave me an error saying "Provider keyword not supported". To attempt to debug this error, I tried the following

 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")

现在,我得到了一个错误说不支持元数据关键字。所以我改变了我的code到

Now, I got an error saying "metadata keyword not supported". So I changed my code to

MyClassDBContext a = new MyClassDBContext("provider=System.Data.SqlClient;provider connection string=user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30")

现在我得到了一个错误说不支持的提供关键词。于是,我又改变了我的code到

Now I got an error saying "provider keyword not supported". So I again changed my code to

 MyClassDBContext a = new MyClassDBContext("user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30")

和现在的作品!我的问题是:我怎么在运行时指定供应商和元数据?它看起来像只连接字符串被接受。我使用实体4.3.1从的NuGet。

and now it works!. My question is : how do I specify the provider and metadata at runtime? It looks like only the connection string is being accepted. I am using Entity 4.3.1 from Nuget.

感谢

推荐答案

根据EDMX文件EF要求提供者和元数据的内容。 code-第一款基于EF不需要这个,只需要常规的连接字符串。你可以使用(而不是 EntityConnectionStringBuilder )一个 SqlConnectionBuilder 来建立这种正常的连接字符串,如果你愿意的话。但正如你所看到的,你只需要指定实际连接的详细信息。不需要在EF 4.3.1的的DbContext code-第一范式提供者和元数据。

edmx file based EF require the "Provider" and "Metadata" content. Code-first based EF doesn't require this, requiring only the regular connection string. You could use a SqlConnectionBuilder (instead of EntityConnectionStringBuilder) to build this normal connection string if you'd like. But as you've seen, you need only specify the actual connection details. The Provider and Metadata aren't needed in EF 4.3.1's DbContext Code-first paradigm.

这篇关于实体框架运行时的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆