11

I have a Sitecore template MyTemplate and a corresponding Glass model MySite.Model.MyTemplate.

In my page code, I retrieve a raw Sitecore.Data.Items.Item object from a legacy data access class. This object represents an item of the template MyTemplate, but it is still a generic item object, so I have to access its fields like this: item["FieldName"].

Is there a quick way to convert this Item object into a strongly-typed Glass model of the class MySite.Model.MyTemplate? I want to do this directly in my page code, without replacing the way in which I obtain the item object.

11

Instantiate a SitecoreContext and call the Cast<T>() method.

ISitecoreContext context = SitecoreContext.GetFromHttpContext();
var myTemplateObject = context.Cast<MySite.Model.MyTemplate>(item);
  • 1
    Thank you! And wouldn't it be even better to get the context like this instead? var context = SitecoreContext.GetFromHttpContext(); – Dmytro Shevchenko Sep 26 '16 at 10:30
  • @DmytroShevchenko Yes probably, as it seems to cache stuff. :) – Thomas D Sep 26 '16 at 10:36
6

Looks like SitecoreContext.GetFromHttpContext() is obsolete.

The recommend way is SitecoreContextFactory.Default.GetSitecoreContext()

My preferred way is new SitecoreContext()

So casting can be done like:

var model = SitecoreContextFactory.Default.GetSitecoreContext().Cast<T>(item);
var model = new SitecoreContext().Cast<T>(item);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.