Episerver Commerce - Retrieving all parent catalog nodes
Mari Jørgensen
02.09.2016 01.51.48
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:
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