Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching Linq Query Question

I am creating a forum package for a cms and looking at caching some of the queries to help with performance, but I'm not sure if caching the below will help/do what it should on the below (BTW: Cachehelper is a simple helper class that just adds and removes from cache)

          // Set cache variables
        IEnumerable<ForumTopic> maintopics;

        if (!CacheHelper.Get(topicCacheKey, out maintopics))
        {
            // Now get topics
            maintopics = from t in u.ForumTopics
                          where t.ParentNodeId == CurrentNode.Id
                          orderby t.ForumTopicLastPost descending
                          select t;
            // Add to cache
            CacheHelper.Add(maintopics, topicCacheKey);
        }
        //End Cache

        // Pass to my pager helper
        var pagedResults = new PaginatedList<ForumTopic>(maintopics, p ?? 0, Convert.ToInt32(Settings.ForumTopicsPerPage));

        // Now bind
        rptTopicList.DataSource = pagedResults;
        rptTopicList.DataBind();

Doesn't linq only execute when its enumerated? So the above won't work will it? as its only enumerated when I pass it to the paging helper which .Take()'s a certain amount of records based on a querystring value 'p'

like image 737
YodasMyDad Avatar asked Dec 30 '25 07:12

YodasMyDad


1 Answers

You need to enumerate your results, for example by calling the ToList() method.

maintopics = from t in u.ForumTopics
             where t.ParentNodeId == CurrentNode.Id
             orderby t.ForumTopicLastPost descending
             select t;
// Add to cache
CacheHelper.Add(maintopics.ToList(), topicCacheKey);
like image 186
marcind Avatar answered Jan 01 '26 20:01

marcind