Automapper expression must resolve to top-level member

你。 提交于 2019-11-29 05:31:22

You are using :

 Mapper.CreateMap<Source, Destination>()
 .ForMember( dest => dest.OutputData.Cars, 
             input => input.MapFrom(i => i.Cars)); 

This won't work because you are using 2 level in the dest lambda.

With Automapper, you can only map to 1 level. To fix the problem you need to use a single level :

 Mapper.CreateMap<Source, Destination>()
 .ForMember( dest => dest.OutputData, 
             input => input.MapFrom(i => new OutputData{Cars=i.Cars})); 

This way, you can set your cars to the destination.

  1. Define mapping between Source and OutputData.

    Mapper.CreateMap<Source, OutputData>();
    
  2. Update your configuration to map Destination.Output with OutputData.

    Mapper.CreateMap<Source, Destination>().ForMember( dest => dest.Output, input => 
        input.MapFrom(s=>Mapper.Map<Source, OutputData>(s))); 
    

You can do it that way:

// First: create mapping for the subtypes
Mapper.CreateMap<Source, OutputData>();

// Then: create the main mapping
Mapper.CreateMap<Source, Destination>().
    // chose the destination-property and map the source itself
    ForMember(dest => dest.Output, x => x.MapFrom(src => src)); 

That's my way to do that ;-)

Kevat Shah

The correct answer given by allrameest on this question should help: AutoMapper - Deep level mapping

This is what you need:

Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.OutputData, opt => opt.MapFrom(i => i));
Mapper.CreateMap<Source, OutputData>()
    .ForMember(dest => dest.Cars, opt => opt.MapFrom(i => i.Cars));

When using the mapper, use:

var destinationObj = Mapper.Map<Source, Destination>(sourceObj)

where destinationObj is an instance of Destination and sourceObj is an instance of Source.

NOTE: You should try to move away from using Mapper.CreateMap at this point, it is obsolete and will be unsupported soon.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!