0

My typical build-out for Glass and fluent config is to use an interface and map file (using SitecoreGlassMap) for modeling, but I know if I need to use the model to add data to Sitecore I can't use the interface type. From a best practice standpoint, if my model is to be used for adding content, should I map only to the concrete class? For example, if I have this interface:

public interface ITemplate {
  string Field { get; set; }
}

And then I have this mapping:

public class TemplateMap : SitecoreGlassMap<ITemplate> {
  public override void Configure() =>
    Map(config => {
      config.Field(f => f.Field).FieldName("Field");
    });
}

If I need to add a concrete class of Template like so:

public class Template : ITemplate {
  public string Field { get; set; }
}

Will the fluent mapping capture both the interface and the concrete class? Or would I need to reconfigure the map to be SitecoreGlassMap<Template> instead, and I should just use that for all my references to this template? Basically, do I need to go back through my code and change any ITemplate item = GetItem<ITemplate>() reference to use the concrete class instead? I suppose I could create a second mapping file for the concrete class, but that seems redundant and inefficient.

1 Answer 1

1

I've experimented with this a bit, and the answer appears to be changing the type in SitecoreGlassMap to the concrete class. So continuing the example above, the mapping would be:

public class TemplateMap : SitecoreGlassMap<Template> {
  public override void Configure() =>
    Map(config => {
      config.Field(f => f.Field).FieldName("Field");
    });
}

The you can still get the item with:

ITemplate item = SitecoreService.GetItem<ITemplate>(new GetItemByIdOptions(Guid.Parse("{}")));

And create a new item with:

ITemplate newItem = new Template {
  Name = "Test Item"
};

using (new SecurityDisabler()) {
  ITemplate createOrg = SitecoreService.CreateItem<ITemplate>(new CreateByModelOptions {
    Model = newItem,
    Parent = item
  });
}

It's a pretty good solution...at least there's no need for two maps or using attribute configuration on the concrete class to make the mapping work right.

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.