我正在根据级联下拉列表过滤员工数据。如果参数的值为'-1',则表示'所有数据'。例如,如果 departmentid = -1,则用户在下拉列表中选择了所有,对于类别和角色也是如此。
现在我需要使用 EF linq 查询来查询数据库。我的员工实体中有三个外键关联,用于根据所选值获取工作类别、角色和部门的名称。
因此,如果用户为类别和工作角色选择了 -1(全部),它必须查询员工实体并带回所选部门中的所有员工,否则它应该根据所选部门、类别或角色进行过滤。
我不确定如何在不使用三个或 if-else 语句的情况下为此编写简洁的 linq 查询。以下是我目前所拥有的,但如果我采用这种方法,我至少需要使用另外三个 if 语句。
任何帮助将不胜感激 - 谢谢
[HttpGet]
public ActionResult GetEmployees(Models.Department department, Models.Category category, Models.Role role)
{
try
{
if (department.DepId == -1)
{
using (emsCtx)
{
var allResults = (from q in emsCtx.Employees
select new Models.Employee
{
Id = q.Id,
FirstName = q.FirstName,
MiddleName = q.MiddleName,
LastName = q.Lastname,
DOB = q.DOB,
JobTitle = q.Roles.Designation,
JobCategory = q.Categories.Type,
Department = q.Departments.Name,
Salary = q.BasicPay
}).ToList();
employeeData.Employees = allResults;
}
}
else
using (emsCtx)
{
var empResults = (from q in emsCtx.Employees
where department.DepId == q.Department
&& role.RoleId == q.Designation
&& category.CatId == q.Category
select new Models.Employee
{
Id = q.Id,
FirstName = q.FirstName,
MiddleName = q.MiddleName,
LastName = q.Lastname,
DOB = q.DOB,
JobTitle = q.Roles.Designation,
JobCategory = q.Categories.Type,
Department = q.Departments.Name,
Salary = q.BasicPay
}).ToList();
employeeData.Employees = empResults;
}
return View(employeeData);
}