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

C# 如何使用AutoMapper将从FormMember()中的函数调用获得的值传递给另一个函数,c#,.net,automapper,C#,.net,Automapper,在CreateMap()上,我想使用ForMember()中函数调用的返回值,以避免必须调用同一个函数两次 CreateMap<source, destination>() .ForMember(dest => dest.Variable2, opt => opt.MapFrom(src => testFunction(src.Variable1)) .ForMember(dest => dest

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));
CreateMap()
.FormMember(dest=>dest.Variable2,opt=>opt.MapFrom(src=>testFunction(src.Variable1))
.ForMember(dest=>dest.Variable3,opt=>opt.MapFrom(src=>testFunction(src.Variable1));

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

确保在映射属性
Variable3
之前,通过调用
testFunction
来映射例如属性
Variable2

之后,可以从属性
Variable2
中已经设置的值映射属性
Variable3

为此,将
Variable2
的映射顺序设置为eg.1,并为
Variable3
的映射顺序设置更高的值,例如2

下面的示例显示,
testFunction
只运行了一次,因为
Variable2
Variable3
被赋予了相同的
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


请进一步解释一下要求。您想在哪里使用函数调用的结果?@Dimitar,首先感谢您的重播。好吧,就像我说的,我想使用第一个MapFrom到第二个MapFrom的结果(在那个例子中)。换句话说,我想将结果分配到一个变量,然后将其用于另一个FormMember()避免多次调用同一个函数。我认为这是不可能的。传递给
FormMember
的LabDA此时不会执行,而是在映射阶段的稍后执行,因此您不会立即得到执行它的结果。
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; }
}