AutoMapper:从多个源属性映射到集合

Hin*_*ham 6 c# automapper

2018 年 4 月 13 日更新:Automapper 6.1.0 通过引入ReverseMap. 在此处查看发行说明

我正在尝试使用 AutoMapper 来展开对象。

我有一个来源如下

public class Source
{
    public string Name {get;set;}
    public string Child1Property1 {get;set;}
    public string Child1Property2 {get;set;}
    public string Child2Property1 {get;set;}
    public string Child2Property2 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我想将此映射到目的地

public class Destination
{
    public string Name {get;set;}
    public List<Child> Children {get;set;}
}

public class Child
{
    public string Property1 {get;set;}
    public string Property2 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我的映射配置

public static class AutoMapperConfiguration
{
    public static MapperConfiguration Configure()
    {
        var config = new MapperConfiguration(
            cfg =>
            {
                cfg.CreateMap<Source, Destination>()
                    .ForMember(dest => dest.Children, /* What do I put here?*/))
                // I don't think this is correct
                cfg.CreateMap<Source, Child>()
                    .ForMember(dest => dest.Property1, opt => opt.MapFrom(src => src.Child1Property1))
                    .ForMember(dest => dest.Property2, opt => opt.MapFrom(src => src.Child1Property2))
                    .ForMember(dest => dest.Property1, opt => opt.MapFrom(src => src.Child2Property1))
                    .ForMember(dest => dest.Property2, opt => opt.MapFrom(src => src.Child2Property2));

            });
        return config;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我测试我使用的代码时,我mapper.Map<List<Child>>(source)得到了AutoMapperMappingException: Missing type map configuration or unsupported mapping.一个有意义的,因为没有配置到List<Child>. 如果我这样做mapper.Map<Child>(source),我会得到一个Child包含所有的实例null属性值。

不幸的是,我无法修改 Source课程。

AutoMapper 可以做到这一点吗?如果是这样怎么办?

小智 0

您可以在 Source 类上添加一个方法来获取子列表。那么绘制地图就非常容易了。

  • 请提供一个简单的例子 (5认同)