简体   繁体   English

Automapper 一个源到多个目标

[英]Automapper one source to multiple destination

Below is my class下面是我的课

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

I need to map我需要映射

Q1.一季度。 source1 class to Dest1 Class( also i need to map dest2 object) source1 类到 Dest1 类(我也需要映射 dest2 对象)

Edit:编辑:

Q2. Q2。 I need to do map Dest1 back to Source 1 (reverse map)我需要将 Dest1 映射回 Source 1(反向映射)

Am using .net core and auto mapper.. am new to automapper & .net core ..Thanks in advance我正在使用 .net 核心和自动映射器 .. 我是自动映射器和 .net 核心的新手 .. 提前致谢

AutoMapper can map from as many sources to as many destinations as you would like, assuming you configure the mapping.假设您配置了映射,AutoMapper 可以根据需要从任意数量的源映射到任意数量的目的地。 For example, your requested scenario:例如,您请求的场景:

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

Properties with the same name will map automatically.具有相同名称的属性将自动映射。 Any destination properties that don't have a corresponding source property will need to be ignored.任何没有相应源属性的目标属性都需要被忽略。

Once your AutoMapper is configured, you can map as needed with the use of the IMapper interface.配置 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