如何使用AutoMapper按class中定义的顺序映射对象?

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

鉴于这两个对象(我使用非常不同的对象来更好地阐明):

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 定义了 projection 允许映射不同名称的属性:

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

这应该可行,但是:

有什么方法可以直接映射属性,按照它们在class中定义的顺序?:

Brand -> Variety
Speed -> Production

我正在使用 AutoMapper 4.2.1

没有。您所描述的 "order" 只是它们在 C# 源代码中的表达方式。请记住,.NET 编译为中间语言 (IL),然后由 .NET 运行时执行。无法保证您在 C# 中键入字段的顺序与它们在编译为 IL 时发出的顺序相同。

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

否,但您可以显式设置映射顺序,以便某些成员先于其他成员映射。这允许您为一个 属性 提供自定义映射,它可能依赖于您需要已经映射的另一个目的地 属性。

        CreateMap<SourceType, DestType>()
            .ForMember(
                dst => dst.Property1,
                opt.SetMappingOrder(0))
            .ForMember(
                dst => dst.Property2,
                opts =>
                {
                    opts.SetMappingOrder(20);
                    opts.ResolveUsing<ResolverThatNeedsProperty1ToBeMappedAlready>();
                });