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?
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.
Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With