28

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?

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
tobias
  • 1,502
  • 3
  • 22
  • 47
  • 2
    Without AutoMapper you could write: `new ModuleUI {Id = module.Id, ImagePath = module.ImageName, PageUIs = new List(module.Pages.Cast())};` – brgerner Feb 22 '12 at 12:48
  • 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(); - on the ModuleProfile? – AMFerreira Nov 25 '20 at 18:34

1 Answers1

61

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

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
nemesv
  • 138,284
  • 16
  • 416
  • 359