Automapper: Map to Protected Property

2019-04-21 08:10发布

问题:

I need to map to a protected property on a class using Automapper. I've got a public method exposed on this class that is used to set values to the property. This method requires a parameter. How can I map a value to this class?

Destination Class:

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

Here's what my Automapper code (pseudo code) looks like:

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

I need to pass a Billing class to the SetBilling(Billing billing) method. How do I do this? Or, can I just set the protected Billing property?

回答1:

Easiest way: Use AfterMap/BeforeMap constructs.

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

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



回答2:

Also possible: tell AutoMapper to recognize protected members:

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

No extra AfterMap needed. AutoMapper by default looks for public properties, you have to tell it on a global or Profile basis to do something differently (https://github.com/AutoMapper/AutoMapper/wiki/Configuration#configuring-visibility)



标签: c# AutoMapper