AutoMapper - What's difference between Condition and PreCondition

与世无争的帅哥 提交于 2019-12-08 14:57:49

问题


Suppose a mapping using AutoMapper like bellow:

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

What's difference of substitute Condition by PreCondition:

    from.PreCondition(x => ((FromType)x.SourceValue).OtherProperty == "something");

What's the practical difference between this two methods?


回答1:


The diference is that PreCondition is executed before acessing the source value and also the Condition predicate, so in this case, before get the value from MyProperty the PreCondition predicate will run, and then the value from property is evaluated and finally Condition is executed.

In the following code you can see this

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

The output from this program is:

PreCondition
Getting value
Condition

Because the Condition method contains a overload that receives a ResolutionContext instance, that have a property called SourceValue, the Condition evaluate the property value from source, to set the SourceValue property on ResolutionContext object.

ATTENTION:

This behavior work properly until version <= 4.2.1 and >= 5.2.0.

The versions between 5.1.1 and 5.0.2, the behavior is not working properly anymore.

The output in those versions is:

Condition
PreCondition
Getting value


来源:https://stackoverflow.com/questions/40658582/automapper-whats-difference-between-condition-and-precondition

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