AutoMapper: What is the difference between ForMember() and ForPath()?

Adam Shakhabov picture Adam Shakhabov · Aug 5, 2017 · Viewed 15.2k times · Source

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.


Question

Do ForMember and ForPath the same things or when should I use ForPath() over ForMember()?

Answer

Lucian Bargaoanu picture Lucian Bargaoanu · Aug 6, 2017

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 :)