簡體   English   中英

未處理EntityException基礎提供程序無法打開

[英]EntityException was unhandled the underlying provider failed to open

我正在使用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>

您在應用程序中至少提到了兩層(類庫和控制台應用程序)。 N層應用程序要求您具有在Entity Framework所引用的應用程序所有層的web.config / app.config中聲明的EF數據庫的連接字符串。

確保在控制台應用程序app.config和類庫的app.config中列出了數據庫的連接字符串。

根據@Yuliam的上述評論,值得確保連接字符串中包含以下內容:

Integrated security=True;

這是做什么的,當它設置為True時,.Net會嘗試使用當前用戶事件打開連接,如果您指定了用戶和密碼。 如果要以特定用戶身份打開連接字符串,請將Integrated Security設置為False。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM