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

Big*_*ddy 9 c# automapper

我需要使用映射到protected类的属性Automapper.我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");
                }
            }
    }
Run Code Online (Sandbox Code Playgroud)

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

Mapper.CreateMap<PolicyDetail, Policy>()
          .ForMember(d => d.SetBilling(???), 
                          s => s.MapFrom(x => x.Billing));
Run Code Online (Sandbox Code Playgroud)

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

Jim*_*ard 14

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

Mapper.Initialize(cfg =>
{
    // map properties with public or internal getters
    cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
    cfg.CreateMap<Source, Destination>();
});
Run Code Online (Sandbox Code Playgroud)

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


Swa*_*ati 8

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

Mapper.CreateMap<PolicyDetail, Policy>()    
.AfterMap((src, dest) => dest.SetBilling(src.Billing));
Run Code Online (Sandbox Code Playgroud)

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