繁体   English   中英

Automapper 一个源到多个目标

[英]Automapper one source to multiple destination

下面是我的课

class Dest1    
{    
 string prop1;
 string prop2;
 strig prop3;
 public Dest2 Dest2 {get;set;}
 pubic List<Dest3> Dest3 {get;set;}
}

class Dest2    
{   
 string prop4;
 string prop5;
 strig prop6;   
}

class Dest3        
{    
 string prop7;    
}

class Source1

{
 string prop1;
 string prop2;
 string prop3;
 string prop4;
 }
     class Source2
      {
 string prop7;
       }

我需要映射

一季度。 source1 类到 Dest1 类(我也需要映射 dest2 对象)

编辑:

Q2。 我需要将 Dest1 映射回 Source 1(反向映射)

我正在使用 .net 核心和自动映射器 .. 我是自动映射器和 .net 核心的新手 .. 提前致谢

假设您配置了映射,AutoMapper 可以根据需要从任意数量的源映射到任意数量的目的地。 例如,您请求的场景:

var configuration = new MapperConfiguration(cfg =>
    // Mapping Config
    cfg.CreateMap<Source1, Dest2>()
        .ForMember(dest => dest.prop5, opt => opt.Ignore())
        .ForMember(dest => dest.prop6, opt => opt.Ignore());
    cfg.CreateMap<Source1, Dest1>()
        .ForMember(dest => dest.Dest2, opt => opt.MapFrom(src => src));

    // Reverse Mapping Config
    cfg.CreateMap<Dest1, Source1>()
        .ForMember(dest => dest.prop4,
                   opt => opt.MapFrom(src => (src?.Dest2 != null) // ?. w/c#6 
                                             ? src.Dest2.prop4 // map if can
                                             : null)); // otherwise null
);
// Check AutoMapper configuration
configuration.AssertConfigurationIsValid();

具有相同名称的属性将自动映射。 任何没有相应源属性的目标属性都需要被忽略。

配置 AutoMapper 后,您可以根据需要使用 IMapper 接口进行映射。

public class Foo {
    private IMapper _mapper;
    public Foo(IMapper mapper) {
        _mapper = mapper;
    }

    // Map Source1 -> Dest1
    public Dest1 Bar(Source1 source) {
        return _mapper.Map<Dest1>(source);
    }

    // Map Dest1 -> Source1
    public Source1 Baz(Dest1 dest) {
        return _mapper.Map<Source1>(dest);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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