简体   繁体   English

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

[英]Automapper: Map to Protected Property

I need to map to a protected property on a class using Automapper . 我需要使用Automapper到类的protected属性。 I've got a public method exposed on this class that is used to set values to the property. 我在这个类上public了一个public方法,用于为属性设置值。 This method requires a parameter . 此方法需要一个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: 这是我的Automapper代码(伪代码)的样子:

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. 我需要将结算类传递给SetBilling(结算结算)方法。 How do I do this? 我该怎么做呢? Or, can I just set the protected Billing property? 或者,我可以设置受保护的结算属性吗?

Also possible: tell AutoMapper to recognize protected members: 也可以:告诉AutoMapper识别受保护的成员:

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

Easiest way: Use AfterMap/BeforeMap constructs. 最简单的方法:使用AfterMap / BeforeMap构造。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM