然后将EmployeeContext.cs类文件添加到models文件夹,然后将以下代码添加到
公共类EmployeeContext:DbContext
{
public DbSet Employees {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,我做错了什么,所以我无法运行这个项目。
答案 0 :(得分:0)
1.在ConnectionString部分中使用服务器的确切名称。从SQL Server登录页面复制它。 Server Details
<connectionStrings>
<add name="EmployeeContext"
connectionString="server=LAPTOP-J1IQQE3F\SQLEXPRESS; Database=sample; integrated security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
更改&#34;员工&#34;中的代码模型类如下。
使用System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.ComponentModel.DataAnnotations.Schema; 使用System.ComponentModel.DataAnnotations;
命名空间MVCDemo.Models
{ [表(&#34; tblEmployees&#34;)] / *将tablename映射到我们的Modelclass * /
public class EmployeeModel
{
[Key] //If the property is named something other than Id,
//you need to add the [Key] attribute to it.
//Otherwise give error "Entity type has no key defined".
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
}