Unflattening with Automapper

Or… Nested Classes with Automapper
Or…

The Problem

Suppose you have a model like this

    public class Game {
        public string Title { get; set; }
        public Publisher Publisher { get; set; }
        public Platform Platform { get; set; }
    }

    public class Publisher {
        public string Name { get; set; }
    }

    public class Platform {
        public string Name { get; set; }
    }

But you also have an API that receives requests like this

    public class SaveGameRequest {
        public string Title { get; set; }
        public string Publisher { get; set; }
        public string Platform { get; set; }
    }

If you create a mapper from Game to SaveGameRequest, then automapper throws up.

The Solution

What you have to do instead is

  1. Create a mapper from the flat SaveGameRequest to the nested Game
  2. Call ReverserMap()

An Example

Source object:

    {
      "title": "Legend of Zelda: Breath of the Wild",
      "publisher": "Nintento",
      "platform": "Switch"
    }

Should become:

    {
      "Title": "Legend of Zelda: Breath of the Wild",
      "Publisher": {
        "Name": "Nintendo"
      },
     "Platform": {
       "Name": "Switch"
      }
    }

So your mapper will look like:

    var config = new MapperConfiguration(cfg => {
        // Map from flat to nested
        cfg.CreateMap<SaveGameRequest, Game>()
            .ForMember(
                dest => dest.Title,
                opt =>
                    opt.MapFrom(src => src.Title))
            .ForMember(
                dest => dest.Publisher,
                opt =>
                    opt.MapFrom(src => src.Publisher.Name))
            .ForMember(
                dest => dest.Platform,
                opt =>
                    opt.MapFrom(src => src.Platform.Name))
            .ReverseMap(); // <-- Then flip it

    var mapper = new Mapper(config);
    returen mapper.Map<GameSaveRequest>(Game)

More Info: