Automapper expression must resolve to top-level member

前端 未结 5 975
感情败类
感情败类 2020-12-06 09:29

I am using automapper to map source and destination objects. While I map them I get the below error.

Expression must resolve to top-level member. Par

相关标签:
5条回答
  • 2020-12-06 09:55

    This worked for me:

    Mapper.CreateMap<Destination, Source>()
        .ForMember(x => x.Cars, x => x.MapFrom(y => y.OutputData.Cars))
        .ReverseMap();
    
    0 讨论(0)
  • 2020-12-06 09:58

    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.

    0 讨论(0)
  • 2020-12-06 10:03

    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.

    0 讨论(0)
  • 2020-12-06 10:03

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

    0 讨论(0)
  • 2020-12-06 10:12
    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))); 
      
    0 讨论(0)
提交回复
热议问题