blfoley.com - all things development
A simple commerce query for finding products in a category.

Creating a Simple Commerce Query

3/7/2009

For those starting out with Commerce Server 2009, i want to provide a very simple sample of how to perform a simple product query. I will outline each step and prodive details as to what each does.

First we will intialize the query object:
var queryBuilder = new CommerceQuery<Category>();

Next we will tell the query the name of the category we are looking for.
queryBuilder.SearchCriteria.Model.Id = categoryId;

And the catalog they we want to use:
queryBuilder.SearchCriteria.Model.CatalogId = "Adventure Works Catalog";

{
This portion of code is attaching a Related Item query to get the child products.
CommerceQueryRelatedItem<Product> queryChildProducts = new CommerceQueryRelatedItem<Product>(Category.RelationshipName.ChildProducts);

And we will add it to the original query:
queryBuilder.RelatedOperations.Add(queryChildProducts);

}

Now we will execute the query and get our response.
CommerceResponse
response = CommerceFoundationServiceAgent.Execute(queryBuilder);

Now we are going to parse out the correct response as there was only one operation:
CommerceQueryOperationResponse
queryResponse = response.OperationResponses.Single() as CommerceQueryOperationResponse;

Now we have our category object:
Category
category = queryResponse.CommerceEntities.SingleOrDefault();

Now we can create a list of our Products within our category:
IEnumerable<Product> childProducts = category.ChildProducts.GetList<Product>();

I hope this provides a good starting example for a simple commerce query.

Related Postings