0

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?

Jo David
  • 1,696
  • 2
  • 18
  • 20

1 Answers1

4

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.

RvanDalen
  • 1,155
  • 5
  • 10
  • Using the InferType method would probably mean to adjust the t4 templates. I'll try the first method but will definitely check out the other one. – Jo David Sep 15 '15 at 08:51
  • 1
    Mike Edwards has warned against the use of GlassCast in a blog post after this answer had been posted: http://glass.lu/Blog/GlassCast – epik phail Aug 17 '18 at 07:16