自动映射器映射对象

时间:2020-08-30 03:19:28

标签: c# automapper

基于此问题one source to mutiple destination

的其他要求
rev_dict = {}
flipped={}
myDict = {}

def get_key(val):
if val not in flipped:
    flipped[val] = [key]
else:
    flipped[val].append(key)
return(flipped)

myDict.update(dict.fromkeys(['etova ER400', 'enzomac forte','myosone'], 'rack1'))
myDict.update(dict.fromkeys(['etova 200','etogesic ER'], 'rack2'))
search_key = input("Enter name of med : ").lower()
for key, val in myDict.items():
    if key.startswith(search_key):
        print(key, " ---> ", val)
    rev_dict=get_key(val)
print(rev_dict)
  1. 我需要在自动映射器中将Source2映射到Dest1(Dest3是一个列表,也需要映射)

我的映射类:(不起作用)

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 个答案:

答案 0 :(得分:2)

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

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

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

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