Thursday, February 12, 2015

Sitecore Fast Query & LINQ

One of the nicest features of Sitecore is its Fast Query ability (pdf) and its support of IQueryable and LINQ. Being new to Sitecore I was greatly relieved that I wouldn't need to learn yet another query language and could instead use my existing knowledge of LINQ to query Sitecore.

The first task I had to handle was basically implementing a paged list to an MVC view. Pretty common task, familiar to any .NET MVC developer. The only real new thing I had to learn was actual fast query syntax:

    string _query = string.Format("fast:{0}//*[@@id='{1}']//*[@@templateid='{2}']",
        _context.Site.StartPath, pageID.ToString("B"), Templates.Ids.Article);
 
This XPATH type syntax is saying three things.
      Start our search at the site's start path (typically /sitecore/content/home)
      Return all child items of the page
      That have the given template ID (in this case stored in a constants file)

Once we have that fast query we can then order our results, start at the given index, and only take what we need using LINQ. No underlying knowledge of the Sitecore database is needed, it's all just LINQ.

        List<IArticle> GetNextArticles(int startIndex, int rows, Guid pageID)
{
 
    string _query = string.Format("fast:{0}//*[@@id='{1}']//*[@@templateid='{2}']",
        _context.Site.StartPath, pageID.ToString("B"), Templates.Ids.Article);
    
    var _results = _context.Query<IArticle>(_query)
      .OrderByDescending(x => x.ArticleDate)
      .Skip(startIndex)
      .Take(rows).ToList();
    
    if (_results == null)
    {
       return new List<IArticle>();
    }
    else
    {
        return _results;
    }
}

No comments:

Post a Comment