在使用 AutoMapper 映射某些元素时,我有一个独特的要求。
我没有找到任何有效的内置场景解决方案:
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
}
);
此代码不起作用,如果没有值,我不想添加空元素。
有什么线索吗?
对于您的场景,您需要 自定义值解析器 来映射
Contacts
属性的目标成员。
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;
}
}
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()));