具有嵌套子列表的自动映射器

时间:2012-02-22 12:34:10

标签: c# .net c#-4.0 automapper automapper-2

我有以下两个课程:

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; }
}

映射必须如下:

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

如何使用Automapper执行此操作?

1 个答案:

答案 0 :(得分:40)

您可以使用ForMemberMapFromdocumentation) 您的Mapper配置可能是:

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>();

用法:

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

结果:

enter image description here