Geta

Menu NL

Episerver Commerce - Retrieving all parent catalog nodes

From time to time I get asked; 'How can I retrieve all parent catalog nodes for a product in Episerver Commerce?' Achieving this using the current version of Episerver commerce API is a bit cumbersome. Luckily Episerver is working on a relation overhaul for the next major version of Commerce, but until then I'll provide some sample code that does the trick.

Update: Code sample updated to use GetCategories extension method, as suggested by Magnus Rahl in his comment.

Let say you have a product "Puma Green Suede Athletic Sneakers Shoes" with the following categories:

 Product categories

Here is code that lists all nodes (of type NodeContent) that the product belongs to:

private List<string> GetNodes(ProductContent currentContent)
{
List<string> nodeList = new List<string>();
foreach (var nodeRelation in currentContent.GetCategories())
{
var currentNode = _contentLoader.Get<NodeContent>(nodeRelation); if (currentNode != null)
{
AddParentNodes(currentNode, nodeList);
}
}
return nodeList;
}
private void AddParentNodes(NodeContent currentNode, List<string> nodeList)
{
if (currentNode == null)
{
return;
}

if (!nodeList.Contains(currentNode.Code))
{
nodeList.Add(currentNode.Code);
}
var nodeRelations = currentNode.GetCategories().ToList();
nodeRelations.Add(currentNode.ParentLink);
foreach (var nodeRef in nodeRelations)
{
var node = _contentLoader.Get<CatalogContentBase>(nodeRef);
AddParentNodes(node as NodeContent, nodeList);
}
}

 

Hopefully this will be a lot cleaner in the next major version of Episerver Commerce

comments powered by Disqus