13.AutoMapper 之映射前后(Before and After Map Action)

https://www.jianshu.com/p/1ff732094f21

映射前后(Before and After Map Action)

你可能偶尔需要在映射发生前后执行自定义逻辑。这应该很少见,这种操作放在AutoMapper之外更加合理。不过你还是可以使用before/after 映射动作来达到目的:

Mapper.Initialize(cfg => {
  cfg.CreateMap<Source, Dest>()
    .BeforeMap((src, dest) => src.Value = src.Value + 10)
    .AfterMap((src, dest) => dest.Name = "John");
});

或者在映射时创建before/after 映射回调:

int i = 10;
Mapper.Map<Source, Dest>(src, opt => {
    opt.BeforeMap((src, dest) => src.Value = src.Value + i);
    opt.AfterMap((src, dest) => dest.Name = HttpContext.Current.Identity.Name);
});

后一种配置在映射动作前后需要用到关联的上下文信息时很有用。

原文地址:https://www.cnblogs.com/zengpeng/p/11059945.html