Cropping ASP.NET MVC 5 data - does not behave as I expected

I have a view model that I create and then go back to my view. This view model is not cached. However, the view model contains a list of category types that are cached.

I do the usual "If the cache is loaded and returned. If no data is fetched into the cache, store it in the cache and return" the view model to the controller. This works as expected.

My problem is before returning the view model from my controller to my view. I want to update an entry in my category list, but only for the page being called (not for all users / pages that call it). When I do this, it automatically updates the list of categories in the cache and I don't want to do that. I only insert the cache once, so I don't understand why, when I update the list, as soon as I fetch it from the cache, the change is instantly reflected in the cache.

I may not understand how OO / Cache works, but I hope someone can configure me directly?

The code in my controller ...

var vm = new FsmViewModel();
if(vm.ActiveCategoryId > 0)
vm.Categories.Find(c => c.Category_ID == vm.ActiveCategoryId).ActiveBootstrapCss = "active";


Does the above code also update the list of categories that I have saved in the cache? I am using a proxy template to populate a list of categories from a cache or from a database.

ObjectCache cache = MemoryCache.Default;
_categories = (List<Category>)cache[CacheForCategories];

if (_categories != null) return _categories;

// Cache does not exist so create
var policy = new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddHours(4)};

_categories = base.GetAllCategories();
cache.Add(CacheForCategories, _categories, policy);

return _categories;


_categories is returned to my viewmodel pulled from cache or db and is defined in my viewmodel object as

public List<Category> Categories { get; set; }


Can someone please advise me what I am doing wrong here?




source to share

1 answer

You are not doing anything wrong. This is how the cache works out of the box. It contains a reference to the object, not a copy of it. Therefore, if you load an object from the cache, then it is basically the same object, because you only get a reference to it.

You can make a deep copy of your object before storing it in the cache to avoid this.



All Articles