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

雨燕双飞 提交于 2019-12-08 17:07:39

问题


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()?


回答1:


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



来源:https://stackoverflow.com/questions/45524446/automapper-what-is-the-difference-between-formember-and-forpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!