我使用EF构建了一个MVC应用程序。程序运行正常。现在代码在由上下文文件下的EF创建的类中运行。我正在尝试为此设置存储库模式。
上下文代码
public partial class EmpDbEntities : DbContext
{
public EmpDbEntities()
: base("name=EmpDbEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Department> Departments { get; set; }
}
控制器代码
public EmployeeController()
{
db = new EmpDbEntities();
}
// GET: Employee
public ActionResult Index()
{
var employees = db.Employees.Include("Department").ToList();
return View(employees);
}
查看
@model IEnumerable<MVCTestWebApp.Employee>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.EmpName)
</th>
<th>
@Html.DisplayNameFor(model => model.Department.DeptName)
</th>
<th>
@Html.DisplayNameFor(model => model.JoiningDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Active)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.EmpName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Department.DeptName)
</td>
<td>
@Html.DisplayFor(modelItem => item.JoiningDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Active)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.EmpId }) |
@Html.ActionLink("Details", "Details", new { id=item.EmpId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.EmpId })
</td>
</tr>
}
</table>
我想要做的是在Models中有一个Employees类和Department类。同样在Repository Folder中有单独的IRepository接口,包含所有保存,更新和删除的方法。实现接口的一个具体类。最后在控制器中调用它。
但是,当我尝试引用模型类时,它会抛出错误 - 实体类型clsEmployee不是当前上下文的模型的一部分。我尝试更改edmx名称,但它仍然抛出错误。