Or… Nested Classes with Automapper
Or…
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.
What you have to do instead is
SaveGameRequest to the nested GameReverserMap()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)
https://docs.automapper.org/en/stable/Reverse-Mapping-and-Unflattening.html