Ejemplo n.º 1
0
        public async Task <QueryResult <order> > ListAsync(ordersQuery query)
        {
            IQueryable <order> queryable = _context.orders
                                           .Include(p => p.Customer)
                                           .AsNoTracking();

            // AsNoTracking tells EF Core it doesn't need to track changes on listed entities. Disabling entity
            // tracking makes the code a little faster
            if (query.CustomerId.HasValue && query.CustomerId > 0)
            {
                queryable = queryable.Where(p => p.CustomerId == query.CustomerId);
            }

            // Here I count all items present in the database for the given query, to return as part of the pagination data.
            int totalOrders = await queryable.CountAsync();

            // Here I apply a simple calculation to skip a given number of items, according to the current page and amount of items per page,
            // and them I return only the amount of desired items. The methods "Skip" and "Take" do the trick here.
            List <order> orders = await queryable.Skip((query.Page - 1) *query.ItemsPerPage)
                                  .Take(query.ItemsPerPage)
                                  .ToListAsync();

            // Finally I return a query result, containing all items and the amount of items in the database (necessary for client-side calculations ).
            return(new QueryResult <order>
            {
                Orders = orders,
                TotalOrders = totalOrders,
            });
        }
Ejemplo n.º 2
0
        private string GetCacheKeyForordersQuery(ordersQuery query)
        {
            string key = CacheKeys.ordersList.ToString();

            if (query.CustomerId.HasValue && query.CustomerId > 0)
            {
                key = string.Concat(key, "_", query.CustomerId.Value);
            }

            key = string.Concat(key, "_", query.Page, "_", query.ItemsPerPage);
            return(key);
        }
Ejemplo n.º 3
0
        public async Task <QueryResult <order> > ListAsync(ordersQuery query)
        {
            // Here I list the query result from cache if they exist, but now the data can vary according to the Customer ID, page and amount of
            // items per page. I have to compose a cache to avoid returning wrong data.
            string cacheKey = GetCacheKeyForordersQuery(query);

            var orders = await _cache.GetOrCreateAsync(cacheKey, (entry) => {
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
                return(_orderRepository.ListAsync(query));
            });

            return(orders);
        }