我希望将我们当前的API架构转换为更通用的可查询结构,并不要求我们硬盘化每个可能的参数并构建自定义查询。以下是我们当前架构的示例,
[HttpGet]
[Route("Companies/{id:int}/Implementations/Tasks")]
public async Task<IApiResponse<List<CompanyIPTDTO>>> GetCompanyIPTs(int? id = null,
int? taskId = null, int? completedById = null, DateTime? dateCompletedStart = null,
DateTime? dateCompletedEnd = null, int page = 1, int? pageSize = null)
{
// Instantiate generic query
Expression<Func<CompanyIPT, bool>> query = null;
// Check parameters and build the lambda query
// Check if the parameter is given and if the query field is already filled so as to either set or add a query
if (id != null && query != null) query = query.And(t => t.CompanyID == id);
else if (id != null && query == null) query = t => t.CompanyID == id;
if (taskId != null && query != null) query = query.And(t => t.ProcessTaskID == taskId);
else if (taskId != null && query == null) query = t => t.ProcessTaskID == taskId;
if (completedById != null && query != null) query = query.And(t => t.CompletedByID == completedById);
else if (completedById != null && query == null) query = t => t.CompletedByID == completedById;
if ((dateCompletedStart != null && dateCompletedEnd != null) && query != null) query = query.And(a => a.DateCompleted >= dateCompletedStart && a.DateCompleted <= dateCompletedEnd);
else if ((dateCompletedStart != null && dateCompletedEnd != null) && query == null) query = a => a.DateCompleted >= dateCompletedStart && a.DateCompleted <= dateCompletedEnd;
// Execute the GET with the appended query and paging information
var result = _uow.CompanyIPTRepository.List(filter: query, page: page, pageSize: pageSize);
int totalPossibleRecords = _uow.CompanyIPTRepository.GetTotalRecords(filter: query);
return new ApiSuccessResponse<List<CompanyIPTDTO>>(HttpStatusCode.OK, result.Select(x => Mapper.Map<CompanyIPTDTO>(x)).ToList(), result.Count(), Request.RequestUri, totalPossibleRecords, pageSize);
}
正如您所看到的,对于每个get请求上的大型API来说,这都非常麻烦,必须自定义查询检查。我假设必须有一些方法可以基于查询字符串参数来执行此操作。例如,在这种情况下,我希望看到一个看起来像的请求,
https://www.example.com/api/Companies/15/Implementations/Tasks?q=[completedById=5,dateCompletedStart=1/15/18,dateCompletedEnd=1/17/18]
在这样进入后,我假设我们可以构建一些使用Reflection来查看对象并验证这些字段是否存在并构建一个通用查询以命中我们的数据库的东西?
任何人都知道在哪里指出我们正确的方向?