Sami-L
Sami-L

Reputation: 5705

Automapper - Using Resolver to map under condition

Defining a resolver as follows:

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

and mapping the property as follows:

    CreateMap<AppUser, MemberDto>()
        .ForMember(d => d.Image, o => o.MapFrom<MemberAvatarResolver>())

and returning the result as follows:

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

But I am getting a mapping exception:

Unable to create a map expression

Type Map configuration: AppUser -> MemberDto

Destination Member: Image

I've found this solution but it uses an anonymous type instead of DTO/Resolver

Any help on how to implement this case ?

Upvotes: 0

Views: 1130

Answers (1)

Roberto B
Roberto B

Reputation: 582

I see you are using: "ProjectTo". And that only works around Expressions. What you want is not supported.

See documentation on: https://docs.automapper.org/en/latest/Queryable-Extensions.html#supported-mapping-options

Supported mapping options

Not all mapping options can be supported ........

Not supported:

  • MapFrom (Func-based)

.......

Upvotes: 1

Related Questions