开发者

Clear a group of cache in asp.net mvc 3

开发者 https://www.devze.com 2023-04-07 21:37 出处:网络
I am saving a list to cache. so that there is no need to go to the database eache time when the list needs.

I am saving a list to cache. so that there is no need to go to the database eache time when the list needs.

here is the code

  public IEnumerable<SelectListItem> GetCategoriesByParentId(int parentCategoryId)
    {
        string cacheKey = "PC" + parentCategoryId.ToString();
        DateTime expiration = DateTime.Now.AddDays(1);
        IEnumerable<SelectListItem> categoryList ;
        categoryList = HttpContext.Current.Cache[cacheKey] as IEnumerable<SelectListItem>;
        if (categoryList == null)
        {
            categoryList = GetCategoryList(parentCategoryId);      // getting category from database         
            HttpContext.Current.Cache.Add(cacheKey, categoryList, null, expiration, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
        }
        return categoryList;

    }

My problem is when a new category is added to t开发者_开发问答he database ,i am still gettting old category list .the list do not contain new category..How can clear the cache ( only category cache) after adding or changing a category

Any ideas?


When you insert a new category to the database I suppose you have the parent category id into which this category was inserted so you could remove it from the cache:

HttpContext.Current.Cache.Remove("PC" + parentCategoryId);

Now if the adding of a new category is not done by your application and you have no control over it you may take a look at cache expiration with SQL dependency.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号