Automapper with nested child list
Asked Answered
B

1

30

I have two classes below:

public class Module
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ImageName { get; set; }
    public virtual ICollection<Page> Pages { get; set; }
}

public class ModuleUI
{
    public int Id { get; set; }
    public string Text { get; set; }
    public string ImagePath { get; set; }
    public List<PageUI> PageUIs { get; set; }
}

The mapping must be like this:

Id -> Id
Name -> Text
ImageName -> ImagePath 
Pages -> PageUIs

How can I do this using Automapper?

Baseboard answered 22/2, 2012 at 12:34 Comment(2)
Without AutoMapper you could write: new ModuleUI {Id = module.Id, ImagePath = module.ImageName, PageUIs = new List<PageUI>(module.Pages.Cast<PageUI>())};Gaylordgaylussac
Sorry for posting this as an answer, I would prefer to put it as a comment on the solution but due to reputation lower than 50, I couldn't. The elected solution works just fine, and thanks for it! But I keep thinking about one thing: I usually separate the mappings on several profiles, by entity, let's say. So here I would have a ModuleProfile with the Module to ModuleUI mapping settings and a PageProfile with the Page to PageUI mapping settings. On this scenario, how would you do it? Would you still include the - Mapper.CreateMap<Page, PageUI>(); - on the ModuleProfile?Kalamazoo
S
62

You can use ForMember and MapFrom (documentation).
Your Mapper configuration could be:

Mapper.CreateMap<Module, ModuleUI>()
    .ForMember(s => s.Text, c => c.MapFrom(m => m.Name))
    .ForMember(s => s.ImagePath, c => c.MapFrom(m => m.ImageName))
    .ForMember(s => s.PageUIs, c => c.MapFrom(m => m.Pages));
Mapper.CreateMap<Page, PageUI>();

Usage:

var dest = Mapper.Map<ModuleUI>(
    new Module
    {
        Name = "sds",
        Id = 2,
        ImageName = "sds",
        Pages = new List<Page>
        {
            new Page(), 
            new Page()
        }
    });

Result:

enter image description here

Stylobate answered 22/2, 2012 at 12:54 Comment(2)
Yes! AutoMapper threats null values and works for me too!Murillo
Thanks! This answer is still valid after so much years.Thrum

© 2022 - 2024 — McMap. All rights reserved.