Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: Map to Protected Property

Tags:

c#

automapper

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?

like image 993
Big Daddy Avatar asked Dec 19 '14 14:12

Big Daddy


People also ask

Does AutoMapper map private fields?

By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.

Can AutoMapper map enums?

Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.

How does AutoMapper work internally?

How AutoMapper works? AutoMapper internally uses a great concept of programming called Reflection. Reflection in C# is used to retrieve metadata on types at runtime. With the help of Reflection, we can dynamically get a type of existing objects and invoke its methods or access its fields and properties.


1 Answers

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)

like image 95
Jimmy Bogard Avatar answered Sep 25 '22 21:09

Jimmy Bogard