【问题标题】:EntityException was unhandled the underlying provider failed to openEntityException 未处理底层提供程序无法打开
【发布时间】:2014-07-27 05:25:36
【问题描述】:

我正在使用 VisualStudio2012 进行开发。我创建了一个类库EMPDAL,我在其中使用NorthWnd 数据库的Employees 表与Entity Framework 连接,并在配置数据库时测试了连接。我写了下面的代码来获取员工的详细信息。

public class EmplooyeeData
{
    public static List<Employee> GetEmployees( int EmployeeId)
    {
        using (DbEntities dbContext = new DbEntities())
        {
            return dbContext.Employees.Where(x => x.EmployeeID == EmployeeId).ToList();
        }
    }
}

我创建了一个控制台应用程序来使用这个EMPDAL,所以我给出了我的EMPDAL 的引用并使用下面的代码来检索员工详细信息

static void Main(string[] args)
{
   List<EmpDAL.Employee> emp = new List<EmpDAL.Employee>();
   emp = EmpDAL.EmplooyeeData.GetEmployees(1);
}

但是当客户端代码调用GetEmployees(1)并且调试器进入EMPDAL.EmpDataGetEmployess方法然后在return语句中它抛出异常![异常如下所示]

底层提供程序在打开时失败。

AppConfig 我在我的类库和客户端应用程序中使用了相同的。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DbEntities" connectionString="metadata=res://*/EmployeeModel.csdl|res://*/EmployeeModel.ssdl|res://*/EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=localhost;initial catalog=NorthWnd;user id=sa;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>

【问题讨论】:

  • 可能配置中的连接字符串需要从您的 DAL 复制到您的控制台应用程序,内部异常是什么?
  • 我已经在我的帖子中添加了我的 Appconfig 详细信息,并且我正在为我的客户端应用程序使用相同的 appconfig。
  • 能否请您显示内部异常?
  • 内部异常是“底层提供程序在打开时失败。”
  • 尝试在MultipleActiveResultSets=True;之后添加Integrated security=True;

标签: c# entity-framework


【解决方案1】:

您至少提到了您的应用程序的两层(类库和控制台应用程序)。 N 层应用程序要求您在引用实体框架的应用程序的所有层的 web.config / app.config 中声明 EF 数据库的连接字符串。

确保在控制台应用程序 app.config 以及类库的 app.config 中列出了数据库的连接字符串。

根据@Yuliam 的上述 cmets,确保您的连接字符串中有以下内容是值得的:

Integrated security=True;

它的作用是当它设置为 True 时,如果您指定用户和密码,.Net 会尝试打开与当前用户事件的连接。如果要以特定用户身份打开连接字符串,请将 Integrated Security 设置为 False。

【讨论】:

  • 我已经在我的帖子中添加了我的 Appconfig 详细信息,并且我正在为我的客户端应用程序使用相同的 appconfig。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多