You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过GlassMapper获取服务/仓储中已有当前项的子项?

使用GlassMapper获取当前项的子项

方法1:通过模型属性自动映射子项

这是GlassMapper最推荐的用法,直接在你的Glass映射模型中定义子项属性,框架会自动加载关联的子项:

public class CurrentItemModel : GlassBase
{
    // 映射当前项的直接子项,自动识别子项模板对应的模型类型
    [SitecoreChildren(InferType = true)]
    public virtual IEnumerable<ChildItemModel> Children { get; set; }

    // 若不需要强类型,可直接映射为Sitecore原生Item集合
    [SitecoreChildren]
    public virtual IEnumerable<Item> RawChildItems { get; set; }
}

当你获取到当前项的模型实例后,直接访问model.Children就能拿到子项集合,无需额外调用方法。

方法2:用SitecoreService手动查询子项

如果不想通过模型属性映射,可结合Sitecore查询语法,用SitecoreService.GetItems()方法获取:

// 假设已获取当前项的Sitecore Item或Glass模型实例
var currentItem = ...;
var sitecoreService = new SitecoreService(Sitecore.Context.Database);

// 通过当前项的完整路径查询直接子项
var childModels = sitecoreService.GetItems<ChildItemModel>($"{currentItem.Paths.FullPath}/*");

// 若当前项是Glass模型,需先转为原生Item再查询
if (currentItem is GlassBase glassModel)
{
    var childItems = sitecoreService.GetItems<ChildItemModel>(glassModel.Item.Paths.FullPath + "/*");
}

方法3:结合Sitecore原生API转Glass模型

如果已持有Glass模型对应的Sitecore原生Item,可先用Sitecore的GetChildren()获取子项,再映射为Glass模型:

var currentGlassModel = ...;
var sitecoreService = new SitecoreService(Sitecore.Context.Database);

// 先获取原生子项集合,再逐个映射为Glass模型
var childModels = currentGlassModel.Item.GetChildren()
    .Select(item => sitecoreService.GetItem<ChildItemModel>(item));

补充说明

MvcContext和SitecoreService确实没有直接提供GetChildren方法,GlassMapper的设计更偏向于通过模型属性关联数据,而非直接调用类似原生API的方法。SitecoreChildren特性的InferType = true参数会自动根据子项模板匹配对应的Glass模型类型,无需手动指定。

内容的提问来源于stack exchange,提问作者AfshinZavvar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 22:47:40