创建 PersonalChatDto
List<AvatarDto> Avatars
的值并将联系人中的头像添加到其中。var partner = chat.Members.Single(u => u.Id != user.Id);
var contact = await contactRepository.GetContactAsync(user.Id, partner.Id);
var member = await personalChatMemberRepository.GetMemberAsync(chat.Id, user.Id);
var dto = mapper.Map<PersonalChatDto>(chat);
mapper.Map(member, dto);
mapper.Map(partner, dto);
mapper.Map(contact, dto);
return Result<PersonalChatDto>.Success(dto);
问题出在它向我显示的映射配置文件中
var avatars = destMember ?? [];
var contactAvatar = src.CustomAvatar;
所有 props 都有正确的值,甚至返回正确的值。
但是在所有映射之后 dto 的 Avatars 字段是空列表
这是映射配置文件
CreateMap<Contact, PersonalChatDto>()
.ForMember(dest => dest.Id,
opt => opt.Ignore())
.ForMember(dest => dest.FirstName, opt =>
opt.MapFrom(src => src.CustomFirstName))
.ForMember(dest => dest.LastName, opt =>
opt.MapFrom(src => src.CustomLastName))
.ForMember(dest => dest.Avatars, opt =>
opt.MapFrom((src, _, destMember, context) =>
{
var avatars = destMember ?? [];
var contactAvatar = src.CustomAvatar;
if (contactAvatar is null) return avatars;
avatars.Add(context.Mapper.Map<AvatarDto>(contactAvatar));
return avatars;
}));
联系班级
public sealed class Contact : IEntity<Guid>
{
public Guid OwnerId { get; set; }
public User Owner { get; set; }
public Guid UserId { get; set; }
public User User { get; set; }
public string CustomFirstName { get; set; }
public string? CustomLastName { get; set; }
public Guid CustomAvatarId { get; set; }
public ContactAvatar? CustomAvatar { get; set; }
public Guid Id { get; set; } = Guid.NewGuid();
}
个人聊天记录
public sealed record PersonalChatDto(
[Required] Guid Id,
[Required] string UserName,
[Required] string FirstName,
string? LastName,
string? Biography,
List<AvatarDto>? Avatars,
[Required] bool IsMuted)
{
public PersonalChatDto()
: this(default, default!, default!, null, null, null, default)
{
}
};
我试图配置地图配置文件以添加到现有项目列表,而不是设置新值。
您应该通过自动映射器使用 ValueResolver
CreateMap<Contact, PersonalChatDto>()
.ForMember(dest => dest.Id,
opt => opt.Ignore())
.ForMember(dest => dest.FirstName, opt =>
opt.MapFrom(src => src.CustomFirstName))
.ForMember(dest => dest.LastName, opt =>
opt.MapFrom(src => src.CustomLastName))
.ForMember(dest => dest.Avatars, opt => opt.MapFrom<CustomResolver>());
Resolver 类看起来像这样
public class CustomResolver : IValueResolver<Source, Destination, int>
{
public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
{
return source.Value1 + source.Value2;
}
}
您应该根据需要更改 TDestmember
您还应该将此客户解析器注册为程序中的服务。cs
builder.Services.AddTransient<CustomResolver>();
检查https://docs.automapper.org/en/stable/Custom-value-resolvers.html#custom-value-resolvers