利用MVC 5和实体框架我正在尝试为我的索引视图设置一个ViewModel,以显示员工及其目标。 我有一个员工表,一个employeeMap表(带有效负载的连接表)和一个目标表。 Employee和EmployeeMap之间以及Goal和EmployeeMap之间存在一对多的关系。 我是一个新手,并且陷入了索引视图,最初应该显示员工,当选择一名员工时,应该显示员工的目标。
我无法正确执行索引操作:
var viewModel = new EmployeeGoals();
viewModel.Employees = db.Employees
.Include(d => d.Department)
.Include(e => e.Position)
.Include(m => m.EmployeeMaps)
.Where(d => d.OrganizationID == oid && d.Department.ManagerID == currentUser.EmployeeID)
.OrderBy(d => d.HireDate);
if (id != null)
{
ViewBag.EmployeeID = id.Value;
viewModel.EmployeeMaps = viewModel.Employees.Where(e => e.ID == id.Value).Single().EmployeeMaps;
viewModel.Goals = viewModel.EmployeeMaps.Where(e => e.EmployeeID == ViewBag.EmployeeID).Select(e => e.Goals);
}
if (goalID != null)
{
ViewBag.GoalID = goalID.Value;
viewModel.Activities = viewModel.Goals.Where(
x => x.ID == goalID).Single().Activities;
}
return View(viewModel);
我确实正确填充了viewmodel.employees,但没有填充viewmodel.goals
哦,视图模型是:
public class EmployeeGoals
{
public IEnumerable<EmployeeMap> EmployeeMaps { get; set; }
public IEnumerable<Employee> Employees { get; set; }
public IEnumerable<Goal> Goals { get; set; }
}
一个暗示帮助我过去这将是伟大的。 感谢
使用不同的方法让它工作:
viewModel.Employees = db.Employees
.Include(d => d.Department)
.Include(e => e.Position)
.Include(m => m.EmployeeMaps)
.Where(d => d.OrganizationID == oid && d.Department.ManagerID == currentUser.EmployeeID)
.OrderBy(d => d.HireDate);
if (id != null)
{
ViewBag.EmployeeID = id.Value;
viewModel.EmployeeMaps = viewModel.Employees.Where(e => e.ID == id.Value).Single().EmployeeMaps;
viewModel.Goals = from g in db.Goals
join m in db.EmployeeMaps on g.ID equals m.GoalID
join e in db.Employees on m.EmployeeID equals e.ID
where m.EmployeeID == id.Value
select g;
}
无法弄清楚如何使用导航属性获得结果,因此最终得到了上述解决方案。它完成了这项工作,但我经常点击数据库吗?最后,结合了LINQ语法 - 应该只使用其中一个,我知道: - /
答案 0 :(得分:0)
您应该使用SelectMany
:
viewModel.Goals = viewModel.EmployeeMaps
.Where(e => e.EmployeeID == ViewBag.EmployeeID)
.SelectMany(e => e.Goals);
因为EmployeeMaps.Where()
是IEnumerable
,所以Select
会产生IEnumerable<IEnumerable<Goal>>
。 SelectMany
将此展平为IEnumerable<Goal>
。