gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:45:57 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com