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.
精彩评论