You need some caching stratergies, this is a simple cache helper class
using System.Runtime.Caching; public class cacheservice: ICacheservice { public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class { T item = MemoryCache.Default.Get(cacheKey) as T; if (item == null) { item = getItemCallback(); MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10)); } return item; } } interface ICacheService { T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class; }
Using:
cacheservice.GetOrSet("CACHEKEY", (delegate method if cache is empty));
The cache provider checks to see if there is anything named "CACHEKEY" in the cache, and if not, it will call the delegate method to retrieve the data and store it in the cache.
Example:
var Data=cacheService.GetOrSet("CACHEKEY", ()=>SomeRepository.GetData());
In your case, it will be like
var Data=cacheService.GetOrSet("CACHEKEY", Db.BusinessLine.AsQueryable() .Where(x => x.Label.Contains(query)) .Take(10) .Select(x => new { id = x.BusinessLineId, text = x.Label }) .ToList());
You can also customize according to your needs.
Using these caching strategies, it will first load the data and store it in the cache a second time, and will receive the value from the cache instead of going back to the database.
source share