Hello,
How to update/remove certain items in a cache object using IMemoryCache?
When getting cache object, I do below...
[HttpGet] public IEnumerable<string> Get() { string key = "ALLCar-Key"; IList<CarModel> carModelCached = _cache.GetOrCreate(key, entry => { var sampleRecordFromDB = new List<CarModel> { new CarModel() { Id = 10, Name = "Hyundai", Year = 1998 }, new CarModel() { Id = 20, Name = "GMC", Year = 2013 }, new CarModel() { Id = 30, Name = "Subaru", Year = 2019 }, }; return sampleRecordFromDB.ToList(); }); return carModelCached; }
but, if after I do an update/insert, I have to refetch from DB and insert back the updated data to cache.
[HttpPost] public void Post(List<CarModel> car) { string key = "ALLCar-Key"; //fetch from db (removed for brevity...) var sampleRecordFromDB = new List<CarModel> { new CarModel() { Id = 10, Name = "Hyundai", Year = 1998 }, new CarModel() { Id = 20, Name = "GMC", Year = 2020 }, //<<<<------UPDATED VALUE HERE new CarModel() { Id = 30, Name = "Subaru", Year = 2019 }, }; MemoryCacheEntryOptions options = new MemoryCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddDays(1) }; _cache.Set(key, sampleRecordFromDB.ToList(), options); }
My data runs around 150K item, and doing just a simple update to one item then do the cache update is too expensive (performance wise - slow).
Is there a way that I could read from cache and do a single item update/insert from within the cache object?
Thanks,