ASP.. NET MVC实体框架5得到真,假或两者的结果



我有一个要过滤的表。有四个过滤器状态、项目、部门、KPI

KPI是一个布尔值。这个过滤器有三个值。

所以,当过滤器为真时,它应该返回'真'数据,当过滤器为假时,返回'假'数据;当'all'同时返回真数据和假数据时。

我的代码附在下面,我如何增强这个代码?我可以写out if else条件

吗?
var result = new List<TaskMaster>();
bool kpidata;
if (request.IsKPI == 1) { kpidata = true; } else { kpidata = false; }
//For KPI Tasks
if (request.IsKPI == 1 || request.IsKPI == 0)
{
result = await _context.TaskMaster.Where(c => c.IsActive && (c.Status == request.Status || request.Status == "All") && (c.ProjectId == request.ProjectId || request.ProjectId == 0) && (c.IsKPI == kpidata) && (c.AssignedTo.DepartmentId == request.DepartmentId || request.DepartmentId == 0)).Include(y => y.TaskActionLogs)
.Include(y => y.AssignedTo)
.Include(y => y.AssignedBy)
.Include(y => y.Project)
.AsSplitQuery().ToListAsync();
//For Non-KPI Tasks
}
else {
result = await _context.TaskMaster.Where(c => c.IsActive && (c.Status == request.Status || request.Status == "All") && (c.ProjectId == request.ProjectId || request.ProjectId == 0) && (c.AssignedTo.DepartmentId == request.DepartmentId || request.DepartmentId == 0)).Include(y => y.TaskActionLogs)
.Include(y => y.AssignedTo)
.Include(y => y.AssignedBy)
.Include(y => y.Project)
.AsSplitQuery().ToListAsync();
}

修改代码,除了c.IsKPI == kpidata部分,两个查询几乎相同。

删除冗余的几种方法:

  1. 写入IQueryable查询,如果满足条件则追加.Where()。您可以在查询具体化之前追加/扩展查询(通过.ToList(),.First()等)。
var result = new List<TaskMaster>();
bool kpidata;
if (request.IsKPI == 1) { kpidata = true; } else { kpidata = false; }
IQueryable<TaskMaster> query = _context.TaskMaster
.Where(c => c.IsActive 
&& (c.Status == request.Status || request.Status == "All") 
&& (c.ProjectId == request.ProjectId || request.ProjectId == 0) 
&& (c.AssignedTo.DepartmentId == request.DepartmentId || request.DepartmentId == 0));
//For KPI Tasks
if (request.IsKPI == 1 || request.IsKPI == 0)
{
query = query.Where(c => c.IsKPI == kpidata);
}
result = await query.Include(y => y.TaskActionLogs)
.Include(y => y.AssignedTo)
.Include(y => y.AssignedBy)
.Include(y => y.Project)
.AsSplitQuery()
.ToListAsync();

  1. 您也可以将if逻辑迁移到查询中。
&& (!(request.IsKPI == 1 || request.IsKPI == 0) || c.IsKPI == kpidata)

如果!(request.IsKPI == 1 || request.IsKPI == 0)返回true,则省略c.IsKPI == kpidata部分。

result = await _context.TaskMaster
.Where(c => c.IsActive 
&& (c.Status == request.Status || request.Status == "All") 
&& (c.ProjectId == request.ProjectId || request.ProjectId == 0) 
&& (c.AssignedTo.DepartmentId == request.DepartmentId || request.DepartmentId == 0)
&& (!(request.IsKPI == 1 || request.IsKPI == 0) || c.IsKPI == kpidata))
.Include(y => y.TaskActionLogs)
.Include(y => y.AssignedTo)
.Include(y => y.AssignedBy)
.Include(y => y.Project)
.AsSplitQuery()
.ToListAsync();

(request.IsKPI == 1 || request.IsKPI == 0)

也可以修改为:

(new List<int> { 0, 1 }).Contains(request.IsKPI)

相关内容

  • 没有找到相关文章

最新更新