Previous Lecture Complete and continue  

  Inferred Types

The second feature that is available is Inferred Types. Inferred Types allow you to define a base type for the relationship but then derive a more specific type based on the item being mapped.

For example maybe your solutions has a series of child items that are a mixture of events, news, and blog posts:

We want to retrieve these items and we want Glass.Mapper.Sc to automatically map them to a matching type, i.e. Events to an Event class, News to a News class and Blogs to a Blog class.

To achieve this we have to define a base type which for this example we have called Page. We then define our specific types (Event, News, Blog) and make them inherit from the base Page type. The class structure looks like this:

The class diagram:

A model with a property that has the return type Page can make use of type inferring by specifying it as part of the property configuration:

When this property is mapped Glass.Mapper.Sc will check which template an item was created from and then map it to the correct model type. If a matching model type can't be found the it will return the base type.

In the example above the Pages property will contain 1 Event, 1 News and 2 Blog post models. It is then possible to iterate through the collection and cast the item to the correct type:


There are several steps that you must follow when using type inferrring:

  1. Define a common base class.
  2. Create the specific types.
  3. Set a template ID for each type.
  4. Create the listing model.
  5. Preload the configuration into Glass Mapper.

Inferred Types require that configurations for all your Glass.Mapper.Sc models is loaded when Glass.Mapper.Sc initialises. Therefore you must either user the AttributeConfigurationLoader or the FluentConfigurationLoader as described earlier in the course. It is not possible to use OnDemand Loading with Inferred Types.

For an item to be inferred as a more specific type then it must be created directly from the template specified by the template ID, base templates are not supported when inferring type.

If an item you are mapping wasn't created from one of the specific types you have defined then it will be returned as the base type. For example if the Children collection in the above example contained a Product item and no Product class has been defined, then it will be returned as the Page base class. It is possible to filter out these items by using a combination of Template Enforcement and Inferred Types.