Episerver多级嵌套块中获取顶层父块的实现方法咨询
Episerver嵌套子块查找顶层父块实现方案
实现逻辑
通过循环向上遍历内容引用链的方式替换单次查询,每轮查询当前块的直接父引用,直到匹配到顶层父块类型或者无更高层级引用时停止。
代码实现
可以封装为IContentRepository的扩展方法方便调用,示例代码如下:
using EPiServer; using EPiServer.Core; using System.Linq; public static class ContentRepositoryExtensions { /// <summary> /// 从嵌套子块向上查找指定类型的顶层父块 /// </summary> /// <typeparam name="T">顶层父块的类型</typeparam> /// <param name="contentRepository">注入的IContentRepository实例</param> /// <param name="childContentLink">子块的ContentLink</param> /// <returns>匹配到的顶层父块,未找到返回default</returns> public static T GetTopmostParentBlock<T>(this IContentRepository contentRepository, ContentReference childContentLink) where T : BlockData { if (ContentReference.IsNullOrEmpty(childContentLink)) { return default; } ContentReference currentLevelLink = childContentLink; while (true) { // 查询当前内容的直接引用 var references = contentRepository.GetReferencesToContent(currentLevelLink, false).ToList(); if (!references.Any()) { // 无更高层级引用,退出循环 break; } // 取第一个引用的所有者(单引用场景直接使用,多引用场景需补充业务过滤规则) var parentReference = references.First(); if (!contentRepository.TryGet(parentReference.OwnerID, parentReference.OwnerLanguage, out IContent parentContent)) { break; } // 匹配到目标顶层父块类型则返回 if (parentContent is T targetParentBlock) { return targetParentBlock; } // 未匹配则继续向上查找 currentLevelLink = parentContent.ContentLink; } return default; } }
调用示例
你当前场景中要从任意子块查找顶层ParentBlock,直接调用扩展方法即可:
// 示例:从Market块查找顶层ParentBlock var topParentBlock = _contentRepository.GetTopmostParentBlock<ParentBlock>(marketBlock.ContentLink);
适配说明
- 若无固定顶层父块类型,只需移除泛型类型判断,循环至无引用时返回最后一级父内容即可
- 若业务中存在单个块被多个父内容引用的情况,需修改
references.First()逻辑,补充对应过滤规则避免取到错误引用链 - 高频调用场景可自行增加缓存逻辑降低查询性能消耗
内容的提问来源于stack exchange,提问作者Ms1
相关产品推荐
相关产品推荐

