Developer forum

Forum » CMS - Standard features » Getting Query values with IQueryService

Getting Query values with IQueryService

Mafalda Correa
Mafalda Correa
Reply

Hi,

I'm trying to use the results of a Query outside of the QueryPublisher app.

I got this far, but I can't figure out how to retrieve the values I need.

Any ideas on how I can get the fields from the query result?

 

@{
    var queryService = Dynamicweb.Extensibility.ServiceLocator.Current?.GetInstance<IQueryService>();

    if (queryService != null)
    {
        var iQuery = queryService.LoadQuery("Content", "Custom content search.query");
        var composers = queryService.Query(iQuery, new QuerySettings());
        foreach (var composer in composers.QueryResult)
        {
            
            <h1>@composer</h1>
        }
    }
}

Thank you


Replies

 
Morten Bengtson Dynamicweb Employee
Morten Bengtson
Reply
This post has been marked as an answer

Hi Mafalda,

Try to cast the "composer" value to IDictionary<string, object>

Something like this...

var data = composer as IDictionary<string, object>;

if (data != null)
{
    foreach (var entry in data)
    {
        string key = entry.Key;
        object value = entry.Value;
    }
}

However, this will only give you raw values from the index. You would often want to retrieve the actual entities (item, product, user, etc.) from a service...

var data = composer as IDictionary<string, object>;

if (data != null)
{
    object value = null;
    if (data.TryGetValue("Id", value)) // TODO: Change "Id" to whatever the unique identifier is for the entries you are retrieving.
    {
        string id = Convert.ToString(value);
        if (!string.IsNullOrEmpty(id))
        {
            // TODO: Fetch the entity from a service by passing this id. You might want to collect all ids and fetch all the entities at once.
        }
    }
}

 

Best regards,
Morten

Votes for this answer: 1
 
Mafalda Correa
Mafalda Correa
Reply

Thank you!

Yes, all I was missing was actually casting composer to IDictionary<string, object>

Now it works as I expected it to.

 

You must be logged in to post in the forum