1
votes

I'm doing my first dive into ContentSearchAPI with Sitecore 7 but am having a little trouble. For a hypothetical problem, I decided to write a search that indexes the entire tree for my site, pulls out items that are one of two templates and reside in a specific path. The code for the query is:

using (var context = index.CreateSearchContext())
{
    var results = context.GetQueryable<SearchResultItem>()
                 .Where(item => item.TemplateId == GlobalId.UniversalContent
                 || item.TemplateId == GlobalId.UniversalHome)
                 .Where(item => item.Path.Contains("/sitecore/content"))
                 .GetResults();
}

All well and good so far; the search grabs the items needed. But now I want to open the item in editing mode and change the value of a field on said item. Previously when I have worked with Sitecore queries, I use something like the following to accomplish this:

foreach (Item i in itemList)
{
    using (new SecurityDisabler())
    {
        i.Editing.BeginEdit();
        i.Fields["DoNotIndex"].SetValue("1", true);
        i.Editing.EndEdit();
    }
}

But the return type of the LINQ query is SearchResultItem, and as such it does not inherit the Item methods, including Editing.BeginEdit() and the like. I played around with the LINQ query and using Cast() or OfType() in combination with ToList(), but keep getting errors stating that I can't convert SearchResultItem to Item.

Reading up on Sitecore POCO's seems to take me in the right direction, but that seems more about defining fields to read. Is there no way to convert a SearchResultItem to an Item and open the item for editing? With LINQ and ContentSearch API, do I need to create a POCO, define the field I want and then modify it using the POCO?

2

2 Answers

5
votes

What you can do is convert your results into a collection of items:

var itemList= results.Hits.Select(i => i.Document.GetItem());

In that way, you can iterate through each item and edit the field value the way you previously did.

0
votes

You can use below code to do the same -

results = context.GetQueryable<SearchResultItem>()
             .Where(item => item.TemplateId == GlobalId.UniversalContent
                     || item.TemplateId == GlobalId.UniversalHome)
             .Where(item => item.Path.Contains("/sitecore/content"))
             .Select(i => (Item)i.GetItem()).ToList();