使用POCO模板获取Entity Framework的连接字符串

Vac*_*ano 10 .net c# entity-framework app-config

我使用实体框架,我需要获取我的连接字符串,以便我可以构建一个上下文.

我正在使用POCO模板.我的上下文对象有:

string ConnectionString = "name=MyAppConfigConnectionStringPropertyHere"
Run Code Online (Sandbox Code Playgroud)

所以,当我试图构建我的上下文时,它说

"在配置中找不到指定的命名连接,不打算与EntityClient提供程序一起使用,或者无效"

我在这个答案中看到,表明有一个GetConnectionString()方法.但谷歌搜索没有引导我到我需要添加以获取该方法的引用(默认情况下它不在我的项目中).

所以,我不能认为我是第一个想要使用POCO模板获取实体框架的连接字符串的人.别人怎么做到这一点?我想我可以在整个app.config文件中读取并解析出来.但似乎不应该那么难.

任何提示都会很棒!

Yau*_*mal 28

对于实体框架6.0,以下代码给出了当前的ConnectionString.

context.Database.Connection.ConnectionString
Run Code Online (Sandbox Code Playgroud)


dys*_*oko 8

对于不使用EF 4.1的人来说,这是我知道的最简单的方法:

using System.Data.EntityClient;

public static string GetConnectionString(ObjectContext context)
{
    return ((EntityConnection)context.Connection).StoreConnection.ConnectionString;
}
Run Code Online (Sandbox Code Playgroud)


J. *_*hon 1

web.config 中必须存在一个在上下文中使用指定名称的 connectionString 元素:

<configuration>
     <connectionStrings>
          <add name="MyAppConfigConnectionStringPropertyHere"
               providerName="System.Data.SqlClient"
               connectionString="Data Source...." />
     </connectionStrings>
</configuration>
Run Code Online (Sandbox Code Playgroud)