7/8/2014 - 3:17 PM

Generic GetCached Query

Generic GetCached Query

/// <summary>
/// Generic caching call
/// </summary>
/// <typeparam name="TEntity">Class to map query to</typeparam>
/// <param name="query">Query to be executed</param>
/// <param name="CacheKey">Unique key used for reference on server</param>
/// <param name="CacheDurationSeconds">Duration for data to remain cached</param>
/// <returns> List of queried object</returns>
public IList<TEntity> GetCached<TEntity>(IQueryable<TEntity> query, string CacheKey, int CacheDurationSeconds) {
    IList<TEntity> list = System.Web.HttpRuntime.Cache[CacheKey] as IList<TEntity>;

    if (list != null)
        return list as IList<TEntity>;

    list = query.ToList();

    System.Web.HttpRuntime.Cache.Insert(CacheKey, list, null, DateTime.Now.AddSeconds(CacheDurationSeconds), System.Web.Caching.Cache.NoSlidingExpiration);

    return list as IList<TEntity>;

//var q = db.UserDetails.Where(x => x.UserId == userId);
//Model.UserDetails r = GetCached<Model.UserDetails>(q, string.Format("User-Details-{0}", userId), 300).FirstOrDefault();