自动映射:映射到受保护的属性

我需要使用Automapper到类的protected属性。 我在这个类上public了一个public方法,用于为属性设置值。 此方法需要parameter 。 如何将值映射到此类?

目的地类:

 public class Policy { private Billing _billing; protected Billing Billing { get { return _billing; } set { _billing = value; } } public void SetBilling(Billing billing) { if (billing != null) { Billing = billing; } else { throw new NullReferenceException("Billing can't be null"); } } } 

这是我的Automapper代码(伪代码)的样子:

 Mapper.CreateMap() .ForMember(d => d.SetBilling(???), s => s.MapFrom(x => x.Billing)); 

我需要将结算类传递给SetBilling(结算结算)方法。 我该怎么做呢? 或者,我可以设置受保护的结算属性吗?

最简单的方法:使用AfterMap / BeforeMap构造。

 Mapper.CreateMap() .AfterMap((src, dest) => dest.SetBilling(src.Billing)); 

https://github.com/AutoMapper/AutoMapper/wiki/Before-and-after-map-actions

也可以:告诉AutoMapper识别受保护的成员:

 Mapper.Initialize(cfg => { // map properties with public or internal getters cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly; cfg.CreateMap(); }); 

没有额外的AfterMap需要。 默认情况下,AutoMapper会查找公共属性,您必须在全局或配置文件的基础上告诉它以不同的方式执行操作( https://github.com/AutoMapper/AutoMapper/wiki/Configuration#configuring-visibility