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
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>();
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With