public async Task <QueryResult <BudgetLevel> > ListAsync(BudgetLevelQuery query) { IQueryable <BudgetLevel> queryable = _context.BudgetLevels .Include(p => p.User) .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.UserId.HasValue && query.UserId > 0) { queryable = queryable.Where(p => p.UserId == query.UserId); } // Here I count all items present in the database for the given query, to return as part of the pagination data. int totalItems = 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 <BudgetLevel> BudgetLevels = 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 <BudgetLevel> { Items = BudgetLevels, TotalItems = totalItems, }); }
private string GetCacheKeyForBudgetLevelQuery(BudgetLevelQuery query) { string key = CacheKeys.BudgetLevelsList.ToString(); if (query.UserId.HasValue && query.UserId > 0) { key = string.Concat(key, "_", query.UserId.Value); } key = string.Concat(key, "_", query.Page, "_", query.ItemsPerPage); return(key); }
public async Task <QueryResult <BudgetLevel> > ListAsync(BudgetLevelQuery query) { // Here I list the query result from cache if they exist, but now the data can vary according to the category ID, page and amount of // items per page. I have to compose a cache to avoid returning wrong data. string cacheKey = GetCacheKeyForBudgetLevelQuery(query); var products = await _cache.GetOrCreateAsync(cacheKey, (entry) => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1); return(_budgetLevelRepository.ListAsync(query)); }); return(products); }