定义解析器如下:
public string Resolve(AppUser source, MemberDto destination, string destMember, ResolutionContext context)
{
if (source.Photos.Count > 0)
{
if (source.Photos.FirstOrDefault(x => x.IsMain) != null)
{
var urlStart = (source.Photos.FirstOrDefault(x => x.IsMain).Url.ToString()).Substring(0, 4);
if (urlStart == "http")
{
return source.Photos.FirstOrDefault(x => x.IsMain).Url;
}
else
{
return _config["ApiUrl"] + source.Photos.FirstOrDefault(x => x.IsMain).Url;
}
}
}
return null;
}
并按如下方式映射属性:
CreateMap<AppUser, MemberDto>()
.ForMember(d => d.Image, o => o.MapFrom<MemberAvatarResolver>())
并返回如下结果:
public async Task<PagedList<MemberDto>> GetMembersAsync(UserParams userParams)
{
var query = _context.Users
.Include(p => p.Photos)
.AsQueryable();
var mappedEntity = query.ProjectTo<MemberDto>(_mapper
.ConfigurationProvider, new { Image = query.Select(u => u.Photos.FirstOrDefault(x => x.IsMain).Url)});
return await PagedList<MemberDto>.CreateAsync(mappedEntity,
userParams.PageNumber, userParams.PageSize);
}
但是我得到一个映射异常:
无法创建映射表达式
Type Map配置:AppUser ->MemberDto
Destination Member: Image
我已经找到了这个解决方案,但它使用匿名类型而不是DTO/Resolver
关于如何实现这种情况有什么帮助吗?
我看你用的是:"ProjectTo"这只适用于表达式。你想要的是不支持.
参见文档:https://docs.automapper.org/en/latest/Queryable-Extensions.html#supported-mapping-options
支持的映射选项
不支持所有的映射选项........
不支持:
- MapFrom (Func-based)
.......