Using inheritance 

In this tutorial we will look at how we can configure our classes to use inheritance using attribute configuration. It is important to note that fluent configuration works differently which we will cover in a later tutorial.

When you start to build you models you will want to group common properties in to a base class and make you other models inherit from it. For example in our simple solution most of our models use the "Page Title" field and have the items URL and ID. We can extract this into a separate class:

using System;
using Glass.Mapper.Sc.Configuration.Attributes;

namespace Glass.Mapper.Sites.Sc.Models.Misc
{
    [SitecoreType(AutoMap = true)]
    public class ContentBase
    {
        public virtual string Title { get; set; }

        public virtual Guid Id { get; set; }

        public virtual string Url { get; set; }
    }
}

Now that we have the base type defined we can update the NewsArticle class to inherit from it, and remove the properties that now exist on the base type:

using System;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.Fields;
using Glass.Mapper.Sites.Sc.Models.Misc;

namespace Glass.Mapper.Sites.Sc.Models.Content
{
    [SitecoreType]
    public class NewsArticle : ContentBase
    {
        [SitecoreField]
        public virtual string Abstract { get; set; }

        [SitecoreField]
        public virtual string MainBody { get; set; }

        [SitecoreField]
        public virtual Image FeaturedImage { get; set; }

        [SitecoreField]
        public virtual DateTime Date { get; set; }
    }
}

Notice that we have now simplified the NewsArticle configuration so that it only defines the properties that exist on the NewsArticle class itself.

We can also update the HomePage class to inherit from the ContentBase as well.

This completes the this tutorial, we have seen how we can restructure our code to use inheritance and setup the configuration to import the different types.