Exemplo n.º 1
0
        public virtual async Task <ActionResult <IList <TEntity> > > GetAsync()
        {
            List <TEntity> models = await Cache.GetFromRequestAsync <List <TEntity> >(Request);

            if (models != null)
            {
                return(models);
            }

            await Service.AccessEntitiesAsync(async Entities =>
            {
                if (Request.Query.Count == 0)
                {
                    models = await Entities.ToListAsync().ConfigureAwait(false);
                }
                else
                {
                    models = await Entities.ApplyQueryParameters(Request.Query).ToListAsync().ConfigureAwait(false);
                }
            });

            await Cache.AddRequestAsync(Request, models);

            return(models);
        }
Exemplo n.º 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);