Automapper: Map to Protected Property

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

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)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!