public static void PrepareRatings(IMemoryCache cache, BlogContext db, IEnumerable <int> blogs) { var ids = new HashSet <int>(blogs); var result = new Dictionary <int, int>(ids.Count()); var ratingCache = cache.Get <ConcurrentDictionary <int, BlogRatingDisplay> >("Rating~") ?? new ConcurrentDictionary <int, BlogRatingDisplay>(); var uncached = ids.Where(i => !ratingCache.ContainsKey(i)); if (uncached.Count() > 0) { var rates = db.BlogRatings.Where(r => uncached.Contains(r.BlogID)) .Select(r => new { r.BlogID, r.value }) .GroupBy(r => r.BlogID) .ToList() .Select(r => new BlogRatingDisplay { BlogId = r.Key, CountByRating = r.GroupBy(br => br.value).ToDictionary(v => v.Key, v => v.Count()) }) .ToDictionary(r => r.BlogId); foreach (var id in uncached) { BlogRatingDisplay br; if (!rates.TryGetValue(id, out br)) { br = new BlogRatingDisplay { BlogId = id }; } ratingCache.TryAdd(id, br); } } cache.Set("Rating~", ratingCache, new MemoryCacheEntryOptions { Priority = CacheItemPriority.High }); }
public BlogRatingDisplay GetRating(int id, bool fromcache = true) { var ratings = _cache.Get <ConcurrentDictionary <int, BlogRatingDisplay> >("Rating~") ?? new ConcurrentDictionary <int, BlogRatingDisplay>(); if (!ratings.TryGetValue(id, out BlogRatingDisplay rating) || fromcache == false) { var rates = _db.BlogRatings.Where(r => r.BlogID == id); rating = new BlogRatingDisplay { BlogId = id, CountByRating = rates.GroupBy(r => r.value).ToDictionary(v => v.Key, v => v.Count()), }; ratings.AddOrUpdate(id, rating, (i, old) => rating); _cache.Set("Rating~", ratings, new MemoryCacheEntryOptions { Priority = CacheItemPriority.High }); } return(rating); }