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

巧了我就是萌 提交于 2019-12-13 02:49:39

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/35748996/how-to-use-automapper-to-map-objects-by-order-defined-in-the-class

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