问题描述
我正在阅读AutoMapper的ReverseMap()
,但无法理解ForMember()
和ForPath()
之间的区别.在此处中描述了实现.根据我的经验,我在ForMember()
上取得了成就.
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);
}
正在工作.
ForMember
和ForPath
是否相同,或者何时应该在ForMember()
上使用ForPath()
?
Do ForMember
and ForPath
the same things or when should I use ForPath()
over ForMember()
?
推荐答案
在这种情况下,为避免不一致,ForPath在内部转换为ForMember.尽管@IvanStoev所说的是有道理的,但另一种查看方式是ForPath是ForMember的子集.因为您可以在ForMember中做更多的事情.因此,当您拥有成员时,请使用ForMember;当您拥有路径时,请使用ForPath:)
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 :)
这篇关于AutoMapper:ForMember()和ForPath()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!