Sitecore: Generic GlassMapper GetChildren<T> Method
本文关键字:gt Method lt GlassMapper GetChildren Sitecore Generic | 更新日期: 2023-09-27 18:12:33
我想创建一个通用方法来获得t的玻璃铸造项目
我现在看到的是:
private static List<T> GetChildren<T>(Item parentItem) where T: class {
var lstChildItems = parentItem.Children.Where(child => child.TemplateID.Equals(T.TemplateId)).ToList();
List<T> lstChildren = lstChildItems.Select(c => c.GlassCast<T>()).ToList();
return lstChildren;
}
在我的例子中,T.TemplateId
不能被解析,因为T
只被标记为class
。TemplateId
是否存在于某种界面中,或者我需要输入什么来代替class
?
如果您想获得TypeConfiguration:
var ctx = new SitecoreContext();
var typeConfig = ctx.GlassContext.TypeConfigurations[typeof(T)];
var templateId = (config as SitecoreTypeConfiguration).TemplateId;
//ofc check for nulls, but you get the point
但是我个人喜欢利用InferType的可能性:
public interface ISitecoreItem
{
[SitecoreChildren(InferType = true)]
IEnumerable<ISitecoreItem> Children { get; set; }
}
[SitecoreType]
public class News : ISitecoreItem
{
public string Title { get; set; }
public virtual IEnumerable<ISitecoreItem> Children { get; set; }
}
private static IEnumerable<T> GetChildren<T>(this Item parentItem) where T : ISitecoreItem
{
var parentModel = item.GlassCast<ISitecoreItem>();
return parentModel.Children.OfType<T>();
}
//usage:
var newsItems = parentItem.GetChildren<News>();
intertype选项将为您提供Glass可以找到的最具体的可用类型。任何从ISitecoreItem派生的东西都可以像这样获取