【发布时间】:2020-12-09 02:32:15
【问题描述】:
在 ASP.NET MVC Web 应用程序中,我创建了以下实体:
[Table("tblEmployee")]
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
但是,当我尝试使用实体框架从名为 tblEmployee 的数据库表中检索数据时,我收到了错误消息。到目前为止我所做的是:
- 用“.”创建了一个数据库
MVCDemo作为服务器名称并使用包含名为tblEmployee的表的 Windows 身份验证 - 已安装的实体框架
- 将
EmployeeContext.cs类文件添加到Models文件夹
代码:
namespace MVCDemo.Models
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
-
为根目录下的web.config文件添加了连接字符串
<connectionSrtings> <add name="EmployeeContext" connectionString="server=.; database=MVCDemo; integrated security=SSPI" providerName="System.Data.SqlClient;" /> </connectionSrtings> -
为 EmployeeController 添加了 Details actionResult 以显示员工详细信息:
namespace MVCDemo.Controllers { public class EmployeeController : Controller { // GET: Employee public ActionResult Details(int id) { EmployeeContext employeeContext = new EmployeeContext(); Employee employee = employeeContext.Employees.Single(e => e.EmployeeId == id); return View(employee); } } }
最后,我在Global.asax 中添加了以下代码来防止初始化:
Database.SetInitializer<MVCDemo.Models.EmployeeContext>(null);
问题是当我运行应用程序时出现此错误:
HTTP 错误 500.19 - 内部服务器错误
请求的页面无法访问,因为该页面的相关配置数据无效。
当我将连接字符串注释掉并尝试到达时
http://localhost:60613/Employee/Details/1
要显示第一个员工的详细信息,我收到此错误:
System.Data.Entity.Core.EntityException: '底层提供程序在打开时失败。'SqlException: 无法附加文件'C:\Users\arya\source\repos\MVCDemo\MVCDemo\App_Data\MVCDemo.Models。 EmployeeContext.mdf' 作为数据库'MVCDemo.Models.EmployeeContext'。
【问题讨论】:
标签: sql asp.net sql-server asp.net-mvc