Reputation: 1746
I'd like to create a generic method to get glass casted items of T.
What I have so far is:
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;
}
In my example T.TemplateId
can't be resolved because T
is only marked as class
. Does TemplateId
exist in some kind of interface or what do I have to enter instead of class
?
Upvotes: 0
Views: 2596
Reputation: 1155
If you want to get the 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
But I personally like to utilize the InferType possibilities:
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>();
The InferType option will give you the most specific available Type that Glass can find. So anything deriving from ISitecoreItem can be fetched like this.
Upvotes: 4