I have the SQL Products table migrated from MongoDb and I use ASP Core + MediatR. The filtering data comes from frontend Autocompletes where user can select multiple values (3 different ProductGroups + 2 different Suppliers for example). Wanted to ask is my implementation optimal, or did I miss something?
Below the code for action:
[HttpPut("[action]")]
public async Task<IQueryable<ArticleDto>> Put([FromBody] ProductsQueryAll query)
{
var response = await _mediator.Send(query);
return response;
}
And below the code for MediatR model and Handler:
public class ProductsQueryAll : IRequest<IQueryable<ArticleDto>>
{
public string[] ProductGroups { get; set; }
public int[] SupplierIds { get; set; }
public string[] Categories { get; set; }
}
public class ProductsQueryAllHandler : IRequestHandler<ProductsQueryAll, IQueryable<ArticleDto>>
{
private readonly DbContext _dbContext;
private readonly IMapper _mapper;
public ProductsQueryAllHandler(DbContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}
public Task<IQueryable<ArticleDto>> Handle(ProductsQueryAll request, CancellationToken cancellationToken)
{
var predicate = PredicateBuilder.True<ArticleDm>();
if (request.ProductGroups?.Length > 0)
{
predicate = predicate.And(x => request.ProductGroups.Any(y => y == x.ProductGroup));
}
if (request.SupplierIds?.Length > 0)
{
predicate = predicate.And(x => request.SupplierIds.Any(y => y == x.SupplierId));
}
if (request.Categories?.Length > 0)
{
predicate = predicate.And(x => request.Categories.Any( y => y == x.Category));
}
var entityList = _dbContext.Articles
.AsNoTracking()
.Where(predicate);
return Task.FromResult(_mapper.ProjectTo<ArticleDto>(entityList));
}
}
IQueryablewould be enough as well. usePredicateBuilderif you have complex query. \$\endgroup\$