Querying Lucene & Returning POCOs

Ok, so here for me is on of the best features in lucinq and sitecore as a combination. Using search to get POCO objects. I am using the GlassMapper since its common and reasonably mature.

I set up the following class:

[SitecoreType(AutoMap = true)]
public class PageContent
{
    [SitecoreId]
    public Guid Id { get; set; }

    [SitecoreField("Page Title")]
    public string PageTitle { get; set; }

    [SitecoreField("Page Subtitle")]
    public string PageSubtitle { get; set; }
}

Then used the following code to query and return results from the sitecore database.

// assuming glass is already set up
ISitecoreService service = new SitecoreService("web");
LuceneSearch search = new LuceneSearch("path to my index");

// get a normal sitecore query builder
ISitecoreQueryBuilder queryBuilder = new SitecoreQueryBuilder();

// use one of the glass mapper extensions to setup the query
queryBuilder.Field<PageContent>(t => t.PageTitle, "*new*");

// get the search result
var sitecoreSearchResult = new GlassSearchResult(service, search.Execute(queryBuilder));

// do something with it
var result = sitecoreSearchResult.GetPagedItems<PageContent>(0, 20);

// as always you can also use the IEnumerable<PageContent>
foreach (PageContent item in result)
{
        Console.WriteLine("Page Title: " + item.PageTitle);
        Console.WriteLine("Page Subtitle: " + item.PageSubtitle);
        Console.WriteLine("Id: " + item.Id);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s