简体   繁体   中英

Automapper with nested child list

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?

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM