【发布时间】:2014-03-11 05:45:02
【问题描述】:
- 在我的 mvc 4 项目中,我通过 nuget 包管理器安装了实体框架
-
然后将 EmployeeContext.cs 类文件添加到模型文件夹中,然后将以下代码添加到该文件夹中
公共类 EmployeeContext : DbContext
{
公共 DbSet 员工 {get;设置;}
}
我添加了命名空间using System.Data.Entity;
3. 现在我在根目录下的 web.config 文件中添加了一个连接字符串:
<connectionStrings>
<add name="EmployeeContext"
connectionString="server=.; database=Sample; integrated security=SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>
4。将“Employee”模型类映射到数据库表,tblEmployee 使用“Table”属性,如下所示。
[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; }
}
并为表属性添加了命名空间“System.ComponentModel.DataAnnotations.Schema”。
5. 我创建了 EmployeeController.cs,其中 ActionMethod Details() 如下所示:
public ActionResult Details(int id)
{
EmployeeContext employeeContext = new EmployeeContext();
Employee employee = employeeContext.Employees.Single(x => x.EmployeeId == id);
return View(employee);
}
6。最后,Global.asax 文件中 Application_Start() 函数中的以下代码。Database.SetInitializer<MVCDemo.Models.EmployeeContext>(null);
并添加了命名空间using System.Data.Entity;
当我构建这个项目时,它显示构建成功并运行这个程序http://localhost/MVC4Demo/Employee/Details/1
我在这个特定的行中遇到错误,说
Employee employee = employeeContext.Employees.Single(x => x.EmployeeId == id);
EntityException was unhandled by the user code
Underlying provider failed an open
当我从 nugget 安装实体框架时,它具有最新版本 6.0.2 我做错了什么,因此我无法运行这个项目。
【问题讨论】:
-
确保连接字符串正确。
-
据我所知,无论我在我的代码中提供什么,我只使用过 connectionString。
-
server=.正确吗?你不应该使用服务器名称而不是.吗? -
其实server=.仅用于本地服务器没有。
-
实际上我已经检查了它不在本地的 sql server 我已经更改了我的数据库所在的 server=QUTED004/SQLEXPRESS 实际。
标签: asp.net-mvc-4