Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AutoMapper to map objects by order defined in the class?

Given this two objects (I use a very different objects to clarify better):

public class Car
{
   public string Brand {get;set;}
   public int Speed {get;set;}
}

public class Apple
{
   public string Variety {get;set;}
   public int Production {get;set;}
}

AutoMapper defines the projection that allows mapping properties with different name:

var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Car, Apple>()
                 .ForMember(dest => dest.Variety, opt => opt.MapFrom( src => src.Brand))
                 .ForMember(dest => dest.Production, opt => opt.MapFrom(src => src.Speed))
        });

This should work but:

Is there any way to map directly the properties in the order they are defined in the class?:

Brand -> Variety
Speed -> Production

I am using AutoMapper 4.2.1

like image 757
anmarti Avatar asked Mar 02 '16 13:03

anmarti


2 Answers

Is there any way to map directly the properties in the order they are defined in the class?

No, but you can explicitly set the mapping order so that some members are mapped before others. This allows you to provide a custom mapping for one property which may rely on another destination property that you need to have already been mapped.

        CreateMap<SourceType, DestType>()
            .ForMember(
                dst => dst.Property1,
                opt.SetMappingOrder(0))
            .ForMember(
                dst => dst.Property2,
                opts =>
                {
                    opts.SetMappingOrder(20);
                    opts.ResolveUsing<ResolverThatNeedsProperty1ToBeMappedAlready>();
                });
like image 80
Chris Walsh Avatar answered Oct 20 '22 06:10

Chris Walsh


No. The "order" you're describing is simply how they are expressed in your C# source code. Remember, .NET compiles down to intermediate language (IL) which is then executed by the .NET Runtime. There's no way to guarantee that the order you typed your fields into C# will be the same order they are emitted when compiled into IL.

like image 36
PatrickSteele Avatar answered Oct 20 '22 07:10

PatrickSteele