c# - Automapper:映射到 protected 属性(property)

标签 c# automapper

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

目标类:

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<PolicyDetail, Policy>()
          .ForMember(d => d.SetBilling(???), 
                          s => s.MapFrom(x => x.Billing));

我需要将 Billing 类传递给 SetBilling(Billing billing) 方法。我该怎么做呢?或者,我可以只设置 protected Billing 属性吗?

最佳答案

也可能:告诉 AutoMapper 识别 protected 成员:

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

不需要额外的 AfterMap。 AutoMapper 默认查找公共(public)属性,您必须在全局或配置文件的基础上告诉它做一些不同的事情 (https://github.com/AutoMapper/AutoMapper/wiki/Configuration#configuring-visibility)

关于c# - Automapper:映射到 protected 属性(property),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27568428/

相关文章:

c# - .NET 4.5 HttpTaskAsyncHandler 上传文件

c# - 在 ITypeConverter 中使用 Automapper

c# - AutoMapper - 如何在单个属性上使用类型转换器

c# - 是否可以向 Rx.Net Timeout 运算符添加自定义消息

c# - 尝试将长字符串提交给 Asp.Net Web Api 2 Controller 方法时出现错误请求

c# - XElement.Load 和 XDocument.Load 之间有什么区别?

c# - 如何使用 C# 和并行扩展并行化顺序任务?

c# - .Net Core 解决方案中每个项目的 Automapper 不同配置文件

C# List.Clear() 方法没有得到正确的响应

c# - 找到了 Automapper 未映射的成员 - 即使在我映射了这些成员之后