public static IQueryable <TEntity> ApplyQueryParameters <TEntity>(this IQueryable <TEntity> queryable, IQueryCollection queryParameters)
            where TEntity : class
        {
            var parameters = QueryableParameters.Build(queryParameters);

            return(parameters.ApplyLinqExpressions <TEntity, IQueryable <TEntity> >(queryable));
        }
Пример #2
0
        /// <summary>
        /// Returns filtered related entity data wrapped in an <see cref="ActionResult" />
        /// </summary>
        /// <example>
        /// <code>
        /// [HttpGet("{id}/carts")]
        /// public async Task<ActionResult<IEnumerable<CartModel>>> GetCarts([FromRoute]string id) =>
        ///     await GetRelatedAsync<CartModel>(id, Request.Query, customer => customer.Carts);
        /// </code>
        /// </example>
        /// <param name="id"></param>
        /// <param name="query"></param>
        /// <param name="relatedExp"></param>
        /// <typeparam name="TRelatedEntity"></typeparam>
        /// <returns></returns>
        protected async Task <ActionResult <IEnumerable <TRelatedEntity> > > GetRelatedAsync <TRelatedEntity>(string id, IQueryCollection query, Expression <Func <TEntity, IEnumerable <TRelatedEntity> > > relatedExp)
            where TRelatedEntity : class
        {
            var result = await GetAsync(id);

            if (result.Value == null)
            {
                return(result.Result ?? BadRequest());
            }

            var entity = result.Value;

            var relatedEntityType   = typeof(TRelatedEntity);
            var queryableParameters = QueryableParameters.Build(query);
            var completeExpression  = queryableParameters.ApplyLinqExpressions <TRelatedEntity, IEnumerable <TRelatedEntity> >(relatedExp);

            if (entity != null)
            {
                return(await Service.AccessEntitiesAsync(async dbSet =>
                {
                    var loadedEntities = await dbSet
                                         .Where(x => x == entity)
                                         .Include((Expression <Func <TEntity, IEnumerable <TRelatedEntity> > >)completeExpression)
                                         .ToListAsync();
                    return loadedEntities.SelectMany(relatedExp.Compile()).ToList();
                }));
            }

            return(default);