Episerver Commerce - Retrieving all parent catalog nodes

Mari Jørgensen 2016-09-02 00:06:00
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