Home > database >  How to use in-memory Caching with API method parameters
How to use in-memory Caching with API method parameters

Time:10-31

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/

CodePudding user response:

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);
    });
  • Related