AutoMapper - Condition和PreCondition之间有什么区别

Gea*_*iro 14 c# automapper

假设使用AutoMapper进行映射,如下所示:

mapItem.ForMember(to => to.SomeProperty, from =>
{
    from.Condition(x => ((FromType)x.SourceValue).OtherProperty == "something");
    from.MapFrom(x => x.MyProperty);
});
Run Code Online (Sandbox Code Playgroud)

Precondition的替代条件有何不同:

    from.PreCondition(x => ((FromType)x.SourceValue).OtherProperty == "something");
Run Code Online (Sandbox Code Playgroud)

这两种方法之间的实际区别是什么?

Alb*_*iro 12

不同之处在于Precondition在获取源值和Condition谓词之前执行,因此在这种情况下,在从MyProperty获取值之前,将运行PreCondition谓词,然后计算属性值并最终执行Condition.

在以下代码中,您可以看到这一点

class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Person, PersonViewModel>()
                .ForMember(p => p.Name, c =>
                {
                    c.Condition(new Func<Person, bool>(person =>
                    {
                        Console.WriteLine("Condition");
                        return true;
                    }));
                    c.PreCondition(new Func<Person, bool>(person =>
                    {
                        Console.WriteLine("PreCondition");
                        return true;
                    }));
                    c.MapFrom(p => p.Name);
                });
        });

        Mapper.Instance.Map<PersonViewModel>(new Person() { Name = "Alberto" });
    }
}

class Person
{
    public long Id { get; set; }
    private string _name;

    public string Name
    {
        get
        {
            Console.WriteLine("Getting value");
            return _name;
        }
        set { _name = value; }
    }
}

class PersonViewModel
{
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

该程序的输出是:

PreCondition
Getting value
Condition
Run Code Online (Sandbox Code Playgroud)

因为Condition方法包含一个接收ResolutionContext实例的重载,该实例具有一个名为SourceValue的属性,Condition会从source计算属性值,以在ResolutionContext对象上设置SourceValue属性.

注意:

此行为适用于版本<= 4.2.1和> = 5.2.0.

5.1.1和5.0.2之间的版本,行为不再正常工作.

这些版本的输出是:

Condition
PreCondition
Getting value
Run Code Online (Sandbox Code Playgroud)