2011-09-24 90 views
1

我正在保存一個緩存列表。這樣在列表需要時就不需要進入數據庫eache時間。在asp.net中清除一組緩存mvc 3

這裏是代碼,當一個新的類別被添加到數據庫中

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; 

    } 

我的問題是,我仍然流汗舊的類別列表.the列表不包含新category..How可以清除緩存(只有類別緩存)後添加或更改類別

任何想法?

回答

1

當你插入一個新的類別,我想你必須向其中插入這一類別,你可以從緩存中刪除它的父類ID數據庫:

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

現在,一個新的,如果添加類別不是由你的應用程序完成的,你無法控制它,你可以看看cache expiration with SQL dependency

+0

@ Darin.Thanks for your answer.That code only remove a list list cahe with the category id。對 ?但我想刪除所有的類別列表緩存。因爲更改後的類別可能已添加到已緩存的另一個列表中。所有緩存都由我添加 –

+1

@Null指針,是它刪除單個緩存條目。如果你想刪除所有的緩存條目,例如你可以遍歷它們,並檢查'​​PC'的關鍵統計數據是否被刪除。 –

+0

,我可以設置任何類型的緩存依賴?在添加緩存時,第三個參數是緩存相關性。我現在在那裏提供了null。 –