2011-09-24 91 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。 –