Context based property mapping with UmbMapper

Mo Mapping, Mo Problems

A few weeks ago I wrote an article about my new Umbraco mapping engine UmbMapper. If you haven't read that post please do, and better yet, please download it and give it a try.

There's been a longstanding puzzle I've been trying to solve for a while now with mapping engines. One that I couldn't crack with Ditto and until today I didn't think I could solve it with UmbMapper.

I was wrong :)

The Problem

Consider the following POCO class.

public class Page {

    public string Name { get; set; }

    public string Slug => this.Name.ToUrlSegment();
}

Mapping this kind of class is impossible with conventional reflection-based run-time mappers as there is no way to guarantee that the Name property has a value. You'll get a NullReferenceException and a whole heap of frustration.

You can workaround this with Umbraco but it's not pretty. You could either

  1. Turn Slug into a method which works but makes it impossible to serialize.
  2. Create an event handler to calculate and store the property when saving the doctype. This is oh-so-ugly and means spreading logic all over the place.

The Solution

With UmbMapper you can map these properties in the following manner.

First let's define our class.

public class Page {

    public string Name { get; set; }

    public string Slug { get; set; }
}

And our mapper.

public class PageMap : MapperConfig<Page>
{
    public PageMap()
    {
        this.AddMap(p => p.Name);
        this.AddMap(p => p.Slug).MapFromInstance(i => i.Name.ToUrlSlug());
    }
}

The MapFromInstance method is our friend here. This has the following signature.

/// <summary>
/// Sets the property mapping predicate. Used for mapping from known values in the current instance.
/// </summary>
/// <param name="predicate">The mapping predicate</param>
/// <returns>The <see cref="PropertyMap{T}"/></returns>
public PropertyMap<T> MapFromInstance(Func<T, object> predicate)

With this method we can map any combination of lazy/non-lazy properties at run-time and be guaranteed the correct result and we keep our mapping logic where it belongs.

Fantastic!

Get it While it's Hot!

Give UmbMapper a whirl, it's simple to use but immensely powerful giving you the means to create flexible, scalable Umbraco websites with very little effort.

comments powered by Disqus