I am reading AutoMapper's ReverseMap()
and I can not understand the difference between ForMember()
and ForPath()
. Implementations was described here. In my experience I achieved with ForMember()
.
See the following code where I have configured reverse mapping:
public class Customer
{
public string Surname { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class CustomerDto
{
public string CustomerName { get; set; }
public int Age { get; set; }
}
static void Main(string[] args)
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Customer, CustomerDto>()
.ForMember(dist => dist.CustomerName, opt => opt.MapFrom(src => $"{src.Surname} {src.Name}"))
.ReverseMap()
.ForMember(dist => dist.Surname, opt => opt.MapFrom(src => src.CustomerName.Split(' ')[0]))
.ForMember(dist => dist.Name, opt => opt.MapFrom(src => src.CustomerName.Split(' ')[1]));
});
// mapping Customer -> CustomerDto
//...
//
// mapping CustomerDto -> Customer
var customerDto = new CustomerDto
{
CustomerName = "Shakhabov Adam",
Age = 31
};
var newCustomer = Mapper.Map<CustomerDto, Customer>(customerDto);
}
It is working.
Do ForMember
and ForPath
the same things or when should I use ForPath()
over ForMember()
?
We can map both directions, including unflattening: var configuration = new MapperConfiguration(cfg => { cfg. CreateMap<Order, OrderDto>() . ReverseMap(); });
automapper Profiles Basic Profile Profiles permit the programmer to organize maps into classes, enhancing code readability and maintainability. Any number of profiles can be created, and added to one or more configurations as needed. Profiles can be used with both the static and instance-based APIs.
In this case, to avoid inconsistencies, ForPath
is translated internally to ForMember
. Although what @IvanStoev says makes sense, another way to look at it is that ForPath
is a subset of ForMember
. Because you can do more things in ForMember
. So when you have a member, use ForMember
and when you have a path, use ForPath
:)
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