.net 自动Map器-有条件地将元素Map并添加到列表

kb5ga3dv  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(107)

在使用AutomapperMap某些元素时,我有一个独特的要求。
我没有找到任何有效的解决方案与构建的场景:
1.如果电话号码不为空,我想将电话号码详细信息添加到联系人列表
1.如果电子邮件不为空,我想将电子邮件地址详细信息添加到联系人列表

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
                    }                   
                );

这段代码不起作用,如果没有值,我不想添加空元素。
有线索吗?

thtygnil

thtygnil1#

在您的案例中,您需要Custom Value Resolver来MapContacts属性的目的成员。
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添加Map配置/概要文件以使用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()));

Demo @ .NET Fiddle

相关问题