我之前错了,我从你的代码中看出,之间存在多对多关系Employee
and Work
表。为了方便起见,我使用了Job
作为你的名字Work
表/模型。
我希望你想显示一个列表EmployeeIds
以及相应的EmployeeNames
在索引视图中。我添加了一个名为的额外属性JobName
对于 viewmodel,您还可以拥有其他属性。
为此,创建一个 ViewModelEmployeeViewModel
并绑定index view
你的行动结果IEnumerable<EmployeeViewModel>
。的定义EmployeeViewModel
可以是这样的——
public class EmployeeViewModel
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string JobName { get; set; }
//..Other memberVariables..
}
假设这些是你的模型 -
Employee
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string Address { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
}
And WorkTable
, renamed it as Job
为了我自己的方便
public class Job
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int JobId { get; set; }
public string JobName { get; set; }
public JobCategory JobCategory { get; set; }
public int EmployeeId { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
在索引操作中,您通过连接两个表来创建一个结果集,并将其绑定到IEnumerable<EmployeeViewModel>
并将其作为模型传递给视图。视图应该接收类型的模型IEnumerable<EmployeeViewModel>
正如我之前提到的,所以你需要查询你的实体,它应该是这样的 -
public ActionResult Index()
{
//..something like this..this is IQueryable..
//...convert this to IEnumerable and send this as the model to ..
//..the Index View as shown below..here you are querying your own tables,
//.. Employee and Job,and binding the result to the EmployeeViewModel which
//.. is passed on to the Index view.
IEnumerable<EmployeeViewModel> model=null;
model = (from e in db.Employees
join j in db.Jobs on e.EmployeeId equals j.EmployeeId
select new EmployeeViewModel
{
EmployeeId = e.EmployeeId,
EmployeeName = e.EmployeeName,
JobName = j.JobName
});
return View(model);
}
你的索引视图应该是这样的 -
@model IEnumerable<MyApp.Models.EmployeeViewModel>
@{
ViewBag.Title = "Index";
}
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.EmployeeId)
</th>
<th>
@Html.DisplayNameFor(model => model.EmployeeName)
</th>
<th>
@Html.DisplayNameFor(model => model.JobName)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.EmployeeId)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmployeeName)
</td>
<td>
@Html.DisplayFor(modelItem => item.JobName)
</td>
</tr>
}
</table>
在上述解决方案中,我尝试生成与您类似的情况并解决您的担忧。我希望这能为您带来某种程度的缓解,并帮助您继续前进。将此作为地图并尝试按照路线找到您自己的目的地/解决方案。顺便说一句,很抱歉回复延迟。希望这可以帮助。