自动映射器映射对象 [英] automapper mapping objects

查看:86
本文介绍了自动映射器映射对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此问题的此附加要求一个来源到多个目的地

This additional requirement based on this question one source to mutiple destination

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

    class Dest3        
    {    
     string prop7;    
   string prop8;
    }

 class Source2
 {
 string prop7;
 string prop8;
 }

  1. 我需要在自动映射器中将Source2映射到Dest1(Dest3是一个列表,也需要映射)

我的制图课:(不起作用)

My mappping class:(not working)

 CreateMap<Source2, Dest3>();
            CreateMap<Source2, Dest1>()
                .ForMember(d => d.Dests3 , opt => opt.MapFrom(s => s));

推荐答案

因此,假设发生此映射时,Dests3应该是单个项目列表,则其配置应类似于以下内容:

So, assuming that when this mapping occurs Dests3 should be a single item list, the configuration for this should look something like this:

var configuration = new MapperConfiguration(cfg =>
// Mapping Config
cfg.CreateMap<Source2, Dest1>()
    .ForMember(dest => dest.prop1, opt => opt.Ignore())
    .ForMember(dest => dest.prop2, opt => opt.Ignore())
    .ForMember(dest => dest.prop3, opt => opt.Ignore())
    .ForMember(dest => dest.Dests3, opt => opt.MapFrom(src => 
                                                      new List<Dest3> { 
                                                          new Dest3 {
                                                              prop7 = src.prop7,
                                                              prop8 = src.prop8
                                                          }
                                                      }));

// Check AutoMapper configuration
configuration.AssertConfigurationIsValid();

然后,您可以使用映射器在需要的任何地方处理映射,就像这样:

Then, you can use the mapper to handle the mapping wherever you need, like so:

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

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

这篇关于自动映射器映射对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆