我正在ASP.NET Core Web Api上工作,在这里我想创建一个从用户那里获取多个参数的方法,所有这些参数都是可选的,并返回过滤后的数据。
类似:
public async Task<ReportEntity> GetReportByFilters(StatusEnum paramA, bool paramB, ReportStatusEnum paramC)
{
report = await _context.tbl_Reports.Include(x => x.User)
.Where(x => x.Status == paramA, x.IsDone == paramB, x.ReportStatus == paramC)
.ToListAsync();
return report;
}
这些参数可以解析,也可以不解析,在这种情况下,应删除过滤器。如果没有参数,则应接收所有数据。我该怎么办?
最简单的方法是这样的:
public async Task<ReportEntity> GetReportByFilters(StatusEnum? paramA, bool? paramB, ReportStatusEnum? paramC)
{
var query = _context.tbl_Reports.AsNoTracking();
if (paramA != null)
query = query.Where(x => x.Status == paramA.Value);
if (paramB != null)
query = query.Where(x => x.IsDone == paramB.Value);
if (paramC != null)
query = query.Where(x => x.ReportStatus == paramC.Value);
var report = await query.Include(x => x.User).ToListAsync();
return report;
}