如何使用 AutoMapper 将从 ForMember() 中的函数调用获得的值传递给另一个值

How to pass a value obtained from a function call within a ForMember() into another one using AutoMapper

CreateMap() 我想使用 ForMember() 中函数调用的返回值来避免调用同一个函数两次。

CreateMap<source, destination>()
                .ForMember(dest => dest.Variable2, opt => opt.MapFrom(src => testFunction(src.Variable1))
                .ForMember(dest => dest.Variable3, opt => opt.MapFrom(src => testFunction(src.Variable1));

您可以通过 SetMappingOrder 影响属性映射的顺序。

确保例如。 属性 Variable2 通过调用 testFunction 在 属性 Variable3 被映射之前被映射。
之后,属性Variable3可以从属性Variable2.

中已经设置的值进行映射

为此,请将 Variable2 的映射顺序设置为例如。 1 并给 Variable3 中的一个更高的值,例如。 2.

下面的示例显示 testFunction 只有 运行 一次,因为 Variable2Variable3 被赋予了相同的 Guid 值。

var config = new MapperConfiguration(cfg => { 

    cfg.CreateMap<Source, Destination>()
        .ForMember(
            dest => dest.Variable2, 
            opt => {
                opt.SetMappingOrder(1); // Will be mapped first.
                opt.MapFrom(src => testFunction(src.Variable1));
            })
        .ForMember(
            dest => dest.Variable3, 
            opt => {
                opt.SetMappingOrder(2); // Will be mapped second.
                opt.MapFrom((src, dest) => dest.Variable2);
            });
    });

IMapper mapper = new Mapper(config);

var source = new Source {
    Variable1 = "foo"
    };

var destination = mapper.Map<Destination>(source);

Console.WriteLine($"variable2: {destination.Variable2}");
Console.WriteLine($"variable3: {destination.Variable3}");

// variable2: FOO 377dd1f8-ec1e-4f02-87b6-64f0cc47e989
// variable3: FOO 377dd1f8-ec1e-4f02-87b6-64f0cc47e989

public string testFunction(String arg)
{   
    return $"{arg.ToUpper()} {Guid.NewGuid()}";
}

public class Source
{
    public String Variable1 { get; set; }
}

public class Destination
{
    public String Variable2 { get; set; }
    public String Variable3 { get; set; }
}