0

I am trying to learn about caching in .Net Core and have read about in memory-caching which I found pretty easy. But let's say a method returns all Employees but you don't want to return all of them, but lets say 10 at a time. So the API method would have a parameter.

Can I do that with in-memory caching?

These are the articles that I will follow: https://www.c-sharpcorner.com/article/how-to-implement-caching-in-the-net-core-web-api-application/ https://code-maze.com/aspnetcore-in-memory-caching/

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Malin
  • 145
  • 7
  • Cache works same like a Dictionary. By Key you will receive all data that you set before. If you have pagination and your method returns a block of Employees, by ten people per page, you can make dynamic Key, which will include a number of requested page. For example: $"Employees_page_{numberPage}" – UserName Oct 28 '22 at 11:46

1 Answers1

1

You can paginate the list/queryable before actually caching the items so that the items cache the item's for these combination, and after you ask for more items it'll get these items and cache. And the pagination param values will be provided from the API endpoint.

Pagination example:

public static async Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> source, int pageIndex, int pageSize, bool getOnlyTotalCount = false)
{
    if (source == null)
        return new PagedList<T>(new List<T>(), pageIndex, pageSize);

    //min allowed page size is 1
    pageSize = Math.Max(pageSize, 1);

    var count = await source.CountAsync();

    var data = new List<T>();

    if (!getOnlyTotalCount)
        data.AddRange(await source.Skip(pageIndex * pageSize).Take(pageSize).ToListAsync());

    return new PagedList<T>(data, pageIndex, pageSize, count);
}

Cache the values for pagination combination:

var cacheKey = _cacheManager.PrepareKeyForDefaultCache("cachekey.dataitems.byitemsid.{0}-{1}-{2}", elementId, pageIndex, pageSize);
        
return await _cacheManager.GetAsync(cacheKey, async () =>
        {
            var query = from si in _myItemRepository.Table
                   
    
         where si.SliderId == sliderId
                    orderby si.DisplayOrder
                    select si;
    
        return await query.ToPagedListAsync(pageIndex, pageSize);
    });
Kazi Rahiv
  • 529
  • 3
  • 6