Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper expression must resolve to top-level member

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. Parameter name: lambdaExpression

I am not able resolve the issue.

My source and destination objects are:

public partial class Source
{
        private Car[] cars;

        public Car[] Cars
        {
            get { return this.cars; }
            set { this.cars = value; }
        }
}

public partial class Destination
{
        private OutputData output;

        public OutputData Output
        {            
            get {  return this.output; }
            set {  this.output= value; }
        }
}

public class OutputData
{
        private List<Cars> cars;

        public Car[] Cars
        {
            get { return this.cars; }
            set { this.cars = value; }
        }
}

I have to map Source.Cars with Destination.OutputData.Cars object. Could you please help me in this?

like image 551
Sandeep Reddy Pinniti Avatar asked Jul 24 '12 14:07

Sandeep Reddy Pinniti


4 Answers

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.

like image 63
Patrick Desjardins Avatar answered Nov 08 '22 23:11

Patrick Desjardins


  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))); 
    
like image 41
k0stya Avatar answered Nov 08 '22 22:11

k0stya


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

like image 17
Marcus.D Avatar answered Nov 08 '22 23:11

Marcus.D


This worked for me:

Mapper.CreateMap<Destination, Source>()
    .ForMember(x => x.Cars, x => x.MapFrom(y => y.OutputData.Cars))
    .ReverseMap();
like image 2
Dominus.Vobiscum Avatar answered Nov 08 '22 23:11

Dominus.Vobiscum