12

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.

0

3 Answers 3

11

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

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

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);
0

I'm not sure if this is GlassMapper specific but this works for me in my 9.1

SitecoreService context = new SitecoreService(Sitecore.Context.Database);
MyModel rule = context.GetItem<MyModel>(item);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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