c# - AutoMapper - 条件和前提条件有什么区别

标签 c# automapper

假设像下面这样使用 AutoMapper 的映射:

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

替换条件与前置条件有什么区别:

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

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

最佳答案

不同之处在于 PreCondition 在访问源值和 Condition 谓词之前执行,因此在这种情况下,在从 MyProperty 获取值之前,PreCondition 谓词将运行,然后从评估属性并最终执行条件。

在下面的代码中你可以看到这一点

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

这个程序的输出是:

PreCondition
Getting value
Condition

因为 Condition 方法包含接收 ResolutionContext 实例的重载,该实例具有名为 SourceValue 的属性,Condition 评估来自源的属性值,以在 ResolutionContext 对象上设置 SourceValue 属性。

注意:

此行为在版本 <= 4.2.1 和 >= 5.2.0 之前正常工作。

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

这些版本的输出是:

Condition
PreCondition
Getting value

关于c# - AutoMapper - 条件和前提条件有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40658582/

相关文章:

c# - 为什么我的带有 DispatcherTimer 的简单 wpf C# 应用程序出现内存泄漏?

c# - Trim().Split 在 Contains() 中导致问题

c# - AutoMapper 项目嵌套对象,其中内部对象可为空失败

c# - .Net 5 Windows 和自定义身份验证

C# 'var' 关键字与显式定义的变量

c# - Steam 授权

AutoMapper ConstructServicesUsing 被忽略

automapper - 如何将字符串文字映射到目标属性

c# - 如何在 Controller 中模拟 Automapper (IMapper)

asp.net-mvc - 自动映射器可以使用存储库将外键映射到对象吗?