In a previous post I was presenting Umbrella Models and what they are useful for in DD4T. To recap a bit, we need these generic models when we have Component or Multimedia Links that can point to components based on several Schemas. In such case, we can't say for sure what is the type of the linked Component, and instead we need to use type ModelBase (presented in this post).
In this post I'll present the builders for such polymorphic links. Let's first assume we have a Device model that has a Component link field that accepts several Schemas:
The Device model builder needs to be able to identify the type of the linked RelatedItems and build the right model for it. As such, we have the following code in the DeviceBuilder class:
The code simply invokes an umbrella builder (i.e. RelatedItemBuilder) that knows how to build the actual model Internal Link or External Link. The umbrella builder sample code looks like this:
In this case I chose to filter the type of a Component based on its Schema title. A better solution would be to filter based on Schema root element name. This is not always possible, because the root element name must be changed proactively at the moment when the Schema is created or at least before creating many Components on it.
Based on the Schema title (or root element name), we identify the right builder and, as such, we invoke the respective builder.
In this post I'll present the builders for such polymorphic links. Let's first assume we have a Device model that has a Component link field that accepts several Schemas:
public class Device : ModelBase
{
///
<summary>
///
Could be a heterogenous collection of: Internal Link, External
Link
///
</summary>
public IList<ModelBase> RelatedItems { get; set; }
Device device = new Device(component)
{
RelatedItems = RelatedItemBuilder.Instance.Build(fields.LinkedComponentValues("Right_Related_Items"))
public class RelatedItemBuilder : Builder<IComponent, ModelBase>
{
private static readonly RelatedItemBuilder _instance = new RelatedItemBuilder();
public static RelatedItemBuilder Instance { get { return _instance; } }
private RelatedItemBuilder() {}
public override ModelBase Build(IComponent component)
{
ModelBase model = null;
switch (component.Schema.Title)
{
case Constants.INTERNAL_LINK_SCHEMA:
model = InternalLinkBuilder.Instance.Build(component);
break;
case Constants.EXTERNAL_LINK_SCHEMA:
model = ExternalLinkBuilder.Instance.Build(component);
break;
}
return model;
}
Based on the Schema title (or root element name), we identify the right builder and, as such, we invoke the respective builder.
Comments