0

Sitecore version: 9.3

I am trying to fetch the media components with specific template and having a particular check-box selected using Sitecore query in my code.

I tried the following code snippet:

var selectedIndex = ContentSearchManager.GetIndex("sitecore_master_index");

using (var context = selectedIndex.CreateSearchContext())
{
  var results = context.GetQueryable<SearchResultItem>()
   .Where(x => (Convert.ToString(x.TemplateId).Equals(Constants.UnversionedImageTemplateId, StringComparison.InvariantCultureIgnoreCase) || Convert.ToString( x.TemplateId).Equals(Constants.Jpeg, StringComparison.InvariantCultureIgnoreCase))
    && (x.Fields[Constants.OptimizedCheckFieldName].ValueOrDefault() != 1)
    && x.Path.StartsWith(Constants.MediaLibraryPath)).GetResults();

  int count = results.Count();
}

But on execution, I am getting the following error:

System.NotSupportedException
  HResult=0x80131515
  Message=Invalid Method Call Argument Type: Field - FieldNode - Field: _template - Sitecore.Data.ID. Only constant arguments is supported.
  Source=Sitecore.ContentSearch.Linq
  StackTrace:
   at Sitecore.ContentSearch.Linq.Parsing.ExpressionParser.ValidateMethodCallArguments(IEnumerable`1 arguments)

I saw similar questions here but couldn't make sense of this issue. Appreciate if you can help me to understand as why this is happening.

3

Instead of executing

var results = context.GetQueryable<SearchResultItem>()
    .Where(x => (Convert.ToString(x.TemplateId).Equals(Constants.UnversionedImageTemplateId, StringComparison.InvariantCultureIgnoreCase) 
    || Convert.ToString( x.TemplateId).Equals(Constants.Jpeg, StringComparison.InvariantCultureIgnoreCase))

Use

// maybe Guid.ParseExact depending on the type of `TemplateId`
var unversionedImageTemplateId = ID.Parse(Constants.UnversionedImageTemplateId);
var jpegTemplateId = ID.Parse(Constants.Jpeg);

var results = context.GetQueryable<SearchResultItem>()
  .Where(x => x.TemplateId == unversionedImageTemplateId || x.TemplateId == jpegTemplateId)

Otherwise Sitecore tries to pass function down to (I think) Solr.Net and it cannot handle your logic inside the query correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.