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

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

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

Precondition的替代条件有什么区别:

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

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

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

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

 class Program { static void Main(string[] args) { Mapper.Initialize(cfg => { cfg.CreateMap() .ForMember(p => p.Name, c => { c.Condition(new Func(person => { Console.WriteLine("Condition"); return true; })); c.PreCondition(new Func(person => { Console.WriteLine("PreCondition"); return true; })); c.MapFrom(p => p.Name); }); }); Mapper.Instance.Map(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从source计算属性值,以在ResolutionContext对象上设置SourceValue属性。

注意:

此行为正常工作,直到版本<= 4.2.1和> = 5.2.0。

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

这些版本的输出是:

 Condition PreCondition Getting value