user1133512
user1133512

Reputation: 89

MemoryCache overwritten unexpectedly

I'm looking at a problem where I wish to get a collection from an expensive service call and then store it in cache so it can be used for subsequent operations on the UI. The code I'm using is as follows:

 List<OrganisationVO> organisations = (List<OrganisationVO>)MemoryCache.Default["OrganisationVOs"];


        List<Organisation> orgs = new List<Organisation>();
        if (organisations == null)
        {
            organisations = new List<OrganisationVO>();
            orgs = pmService.GetOrganisationsByName("", 0, 4000, ref totalCount);
            foreach (Organisation org in orgs)
            {
                OrganisationVO orgVO = new OrganisationVO();
                orgVO = Mapper.ToViewObject(org);
                organisations.Add(orgVO);
            }

            MemoryCache.Default.AddOrGetExisting("OrganisationVOs", organisations, DateTime.Now.AddMinutes(10));
        }

        List<OrganisationVO> data = new List<OrganisationVO>();
        data = organisations;

        if (!string.IsNullOrEmpty(filter) && filter != "*")
        {
            data.RemoveAll(filterOrg => !filterOrg.DisplayName.ToLower().StartsWith(filter.ToLower()));
        }

The issue I'm facing is that the data.RemoveAll operation affects the cached version. i.e. I want the cached version to always reflect the full dataset returned by the service call. I then want to retrieve this collection from cache whenever the filter is set and apply it but this should not change cached data - i.e. subsequent filters should happen on the full dataset - what is the best way to do this?

Upvotes: 0

Views: 326

Answers (2)

Random Dev
Random Dev

Reputation: 52290

I would either:

  • apply the filter dynamically and replace the filter if needed (so you cache the complete data but only return the cachedData.Where(currentFilter)
  • make two caches - one for the complete data and one for the filtered data - in this case the first one should only consist of the data returned from the service - no need to cache the VO-data as well

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

You need to make copy of the list if you want to use RemoveAll operation (ToList would be enough).

Also instead of modigying the list consider using LINQ operations like Where/Select.

Upvotes: 1

Related Questions