Why should all Glass.Mapper fields be virtual?
Asked Answered
A

1

5

The Glass.Mapper documentation states:

using Glass.Mapper.Sc.Configuration.Attributes;

namespace Glass.Mapper.Sites.Sc.Models.Landing
{
    public class HomePage
    {
        public virtual string Title { get; set; }
        public virtual string MainBody { get; set; }
    }
}

You can see that this class doesn't include any special markup however one important thing to remember when writing class with Glass.Mapper is to ensure that all your fields are marked as virtual. Glass.Mapper can automatically infer what data to load for your model by using a combination of On Demand mapping and Auto-Mapping.

It eludes to use "On-demand" and "Auto-Mapping" but doesn't explain how or why.

Does anyone know why it's important to flag these fields as virtual? It seems to work perfectly fine without this. Nothing I can see inherits the fields and overrides them?

Antepenult answered 13/10, 2015 at 14:23 Comment(2)
Those are properties, not fields.Companionway
I've left it as fields, as that is what the sitecore (incorrectly) call themAntepenult
R
7

If you are using lazy loading, Glass mapper needs to be able to dynamically generate a proxy class on the fly that wraps your class. To be able to inherit and override your properties, they need to be marked virtual.

Raby answered 13/10, 2015 at 15:25 Comment(3)
Sitecore doesn't (that I'm aware of) support lazy loading though? Is this an Umbraco thing?Antepenult
Glass does the lazy loading for you in the Sitecore implementation. At least as much as is possible in Sitecore.Raby
I believe properties also need to be virtual in order to use InferredTypesOnionskin

© 2022 - 2024 — McMap. All rights reserved.