【问题标题】:Entity Framework Connection String Trouble实体框架连接字符串问题
【发布时间】:2010-10-18 19:50:21
【问题描述】:

我正在制作一个小库 (DLL) 来管理用户及其角色/权限。计划是能够将此 dll 添加到 MVC 项目并能够操纵用户/角色/等。所有数据都驻留在 SQL 数据库中。

我正在使用实体框架进行数据访问。

所以当我初始化一个新的 RoleManager(这是我正在制作的 lib 中的主类的名称)时,我会为它提供一个如下所示的 connectionString:

RoleManager roleManager = new RoleManager(string connectionString);

然后在构造函数中我这样做:

db = new RoleManagerEntities(connectionString); //This is the EntityFramework

我正在尝试提供此连接字符串(以及许多其他字符串)

"metadata=res://*/RoleManager.csdl|res://*/RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'"

我收到以下错误:

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.

这个问题是由于尝试从我的新项目中实例化 EF 而不提供连接字符串并且我的应用程序配置中没有任何默认设置的结果。太糟糕了,我现在不能删除它。

【问题讨论】:

    标签: c# sql entity-framework


    【解决方案1】:

    只需将连接字符串信息从您的 DLL 配置文件复制到您的可执行配置文件。

    【讨论】:

    • 我做到了。这就是发生的事情。 “指定的命名连接在配置中找不到,不打算与 EntityClient 提供程序一起使用,或者无效。”
    【解决方案2】:

    基本上,您正在尝试通过此 ObjectContext Constructor (String) 实例化 ObjectContext 而不以预期格式传递字符串参数,这就是问题所在。
    这是您需要做的:

    1. 首先在您的“测试项目”app.config 中创建一个条目,因为这是 CLR 在运行时查找连接字符串的地方。

    <configuration>
      <connectionStrings>
        <add name="RoleManagerEntities" connectionString="metadata=res:///RoleManager.csdl|res:///RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'" />
      </connectionStrings>
    </configuration>
    

    2. 现在更改代码以传递连接字符串 name 而不是实际的连接字符串:
    db = new RoleManagerEntities("name=RoleManagerEntities");
    

    【讨论】:

      【解决方案3】:

      构造函数可能会在您的 web.config 的 connectionStrings 设置中寻找一个连接字符串,并使用您将其作为参数传递的名称。

      所以如果你打电话:

      db = new RoleManagerEntities("Foobar");
      

      它正在寻找:

      我不确定这是解决方案,但这就是错误消息所表明的内容。

      【讨论】:

      • "初始化字符串的格式不符合从索引 0 开始的规范。"错误
      【解决方案4】:

      我不是 EF 专家,但我认为连接字符串无效。试试:

      metadata=res://*;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'
      

      【讨论】:

      • 初始化字符串的格式不符合从索引 0 开始的规范。
      • 但是,如果我使用“provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60;multipleactiveresultsets=true'”那么它说它需要元数据...
      • "指定的命名连接要么在配置中找不到,要么不打算与 EntityClient 提供程序一起使用,要么无效。"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多