entity-framework - Entity Framework 代码优先方法获取错误 : "The underlying provider failed on Open"

标签 entity-framework code-first

我正在尝试使用 Code First Approcah EF 5.0 创建一个简单的数据库。

我有 Employee 类:

public class Employee
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我有 EmployeeDbContext 类:

public class EmployeeDbContext : DbContext
{
    static EmployeeDbContext()
    {            
        Database.SetInitializer<EmployeeDbContext>(null);
    }
    public DbSet<Employee> Employees { get; set; }
}

和 Repository 类:

public class Repository
{
    public List<Employee> GetEmployees()        
    {            
        EmployeeDbContext MyDataBase = new EmployeeDbContext();
        return MyDataBase.Employees.ToList();
    }
}

我已经在其中创建了 WebFrom 文件和一个 GridView,并将其与 ObjectDataSource 连接到存储库(屏幕截图):http://s3.postimg.org/jqvm89scz/Capture.png

这是我的连接字符串:

    <add name="EmployeeDbContext" connectionString="server=.; Database=Sample;Trusted_Connection=True; Persist Security Info=True;" providerName="System.Data.SqlClient" />

当我调试这个时,我在“return MyDataBase.Employees.ToList();”上收到这个错误

An exception of type 'System.Data.Entity.Core.EntityException' occurred in
 EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The underlying provider failed on Open.

我试图在此行之前添加此 MyDataBase.Database.Connection.Open(); 并收到此错误:

Cannot open database "Sample" requested by the login. The login failed.

更新

当我将 ConnectionString 中的数据库更改为现有数据库(Northwind 数据库)时,我只是再次提到我正在尝试创建一个不存在的数据库。

最佳答案

看看这个。此页面上列出了一些连接字符串示例。 https://www.connectionstrings.com/sql-server/

您可以在没有任何 EF 的情况下使用类似这样的代码测试您的连接字符串(这不应引发异常)。

using (SqlConnection connection = new SqlConnection(@"your connection string"))
{
  connection.Open();
}

关于entity-framework - Entity Framework 代码优先方法获取错误 : "The underlying provider failed on Open",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32949355/

相关文章:

entity-framework - 获取SQL以进行自动迁移的策略

entity-framework - EF5 和循环或多级联路径,FOREIGN KEY

c# - 关联属性未加载到实体上

c# - 按多对多关系分组

sql-server - 将SQL数据库从2014版本迁移到2012版本 - mvc codefirst

c# - Entity Framework - 外键组件......不是类型的声明属性

mysql - 原则 2 和垂直划分

c# - 如何使用 AutoMapper 处理 "inflate"实体

c# - 用一个上下文更新一个实体,并在另一个上下文中插入一个新实体?

entity-framework-4 - 如何定义 DatabaseGenerated.Computed 应该计算什么?