简体   繁体   English

AutoMapper:ForMember() 和 ForPath() 有什么区别?

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

I am reading AutoMapper's ReverseMap() and I can not understand the difference between ForMember() and ForPath() .我正在阅读 AutoMapper 的ReverseMap()并且我无法理解ForMember()ForPath()之间的区别。 Implementations was described here . 此处描述实现。 In my experience I achieved with ForMember() .根据我的经验,我使用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() ? ForMemberForPath是否相同,或者我什么时候应该使用ForPath()不是ForMember()

In this case, to avoid inconsistencies, ForPath is translated internally to ForMember .在这种情况下,为了避免不一致, ForPath在内部被转换为ForMember Although what @IvanStoev says makes sense, another way to look at it is that ForPath is a subset of ForMember .虽然什么@IvanStoev说是有道理的,另一种方式来看待它是ForPath的一个子集ForMember Because you can do more things in ForMember .因为你可以在ForMember做更多的事情。 So when you have a member, use ForMember and when you have a path, use ForPath :)因此,当您有成员时,请使用ForMember ,当您有路径时,请使用ForPath :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM