我正在尝试将具有困难结构的对象映射到一个简单的对象:
public class Contact
{
public string ContactName { get; set; }
public IEnumerable<Phone> Phones { get; set; }
}
public class Phone
{
public string Number { get; set; }
public PhoneType Type { get; set; }
}
public enum PhoneType
{
Phone,
Mobile
}
public class ContactDto
{
public string ContactName { get; set; }
public string PhoneNumber { get; set; }
public string MobileNumber { get; set; }
}
Mapper.CreateMap<ContactDto, Contact>()
.ForMember(p => p.Phones.FirstOrDefault(k => k.Type.Equals(PhoneType.Mobile)).Number, r => r.MapFrom(s => s.MobileNumber))
.ForMember(p => p.Phones.FirstOrDefault(k => k.Type.Equals(PhoneType.Phone)).Number, r => r.MapFrom(s => s.PhoneNumber));
但我在标题中有错误。怎么了?
答案 0 :(得分:1)
您的通用参数的顺序是错误的。来源应该是第一个,目的地是后者。
请改为尝试:
Mapper.CreateMap<Contact, ContactDto>()
.ForMember(dto => dto.PhoneNumber, dto => dto.MapFrom(src => src.Phones.First(p => p.Type == PhoneType.Phone).Number))
.ForMember(dto => dto.MobileNumber, dto => dto.MapFrom(src => src.Phones.First(p => p.Type == PhoneType.Mobile).Number));