AutoMapper - 有条件地映射和添加元素到列表

问题描述 投票:0回答:1

在使用 AutoMapper 映射某些元素时,我有一个独特的要求。

我没有找到任何有效的内置场景解决方案:

  1. 如果电话号码不为空,我想将电话号码详细信息添加到联系人列表。
  2. 如果电子邮件不为空,我想将电子邮件地址详细信息添加到联系人列表。
CreateMap<UserModel, UserDefinition>()
              .ForMember(d => d.Id, o => o.Ignore()) 
              .ForMember(d => d.UserName, o => o.MapFrom(s => s.Username))
              .ForMember(d => d.Contacts, o =>  
                  new List<UserContactDefinition>()
                  {
                      o.MapFrom(s => !string.IsNullOrWhiteSpace(s.PhoneNumber) ?
                      new UserContactDefinition
                      {
                          Type = ContactType.Phone,
                          IsPrimary = true,
                          Label = s.PhoneType,
                          Value = s.PhoneNumber
                      }: null,
                      o.MapFrom(s => !string.IsNullOrWhiteSpace(s.ContactEmail) ?
                       new UserContactDefinition
                       {
                           Type = ContactType.Email,
                           IsPrimary = true,
                           Label = s.EmailType,
                           Value = s.Email
                       }: null
                  }                   
              ); 

此代码不起作用,如果没有值,我不想添加空元素。

有什么线索吗?

c# .net automapper mapper
1个回答
2
投票

对于您的场景,您需要 自定义值解析器 来映射

Contacts
属性的目标成员。

  1. 实现
    UserContactDefinitionListResolver
    自定义值解析器。
public class UserContactDefinitionListResolver : IValueResolver<UserModel, UserDefinition, List<UserContactDefinition>>
{
    public List<UserContactDefinition> Resolve(UserModel src, UserDefinition dst, List<UserContactDefinition> dstMember, ResolutionContext ctx)
    {
        dstMember = new List<UserContactDefinition>();
        
        if (!string.IsNullOrWhiteSpace(src.PhoneNumber))
            dstMember.Add(new UserContactDefinition
            {
                Type = ContactType.Phone,
                IsPrimary = true,
                Label = src.PhoneType,
                Value = src.PhoneNumber
            });
            
        if (!string.IsNullOrWhiteSpace(src.ContactEmail))
            dstMember.Add(new UserContactDefinition
            {
                Type = ContactType.Email,
                IsPrimary = true,
                Label = src.EmailType,
                Value = src.ContactEmail
            });
        
        return dstMember;
    }
}
  1. 为成员
    Contacts
    添加映射配置/配置文件以使用
    UserContactDefinitionListResolver
CreateMap<UserModel, UserDefinition>()
    .ForMember(d => d.Id, o => o.Ignore())
    .ForMember(d => d.UserName, o => o.MapFrom(s => s.Username))
    .ForMember(d => d.Contacts, o => o.MapFrom(new UserContactDefinitionListResolver()));

演示@.NET Fiddle

© www.soinside.com 2019 - 2024. All rights reserved.