Search code examples
c#automappermongodb-.net-driver

IMongoQueryable throwing error with AutoMapper .ProjectTo() method


The code below gives this error. I recently switched to MongoDb instead of Ef Core. It seems like automapper doesn't get the object inside it but a serialized form "{document}" or anything else. Can't find much about this and also debugged the automapper code but cannot seem to figure out why this happens.

Error:

GetPartyFullName of type Application.Read.Common.Helpers.MapHelpers is not supported in the expression tree GetPartyFullName({document}).

var partiesList = await parties
            .OrderByDescending(x => x.Created)
            .ThenBy(x => x.Name) // this is IOrderedMongoQueryable
            //.AsQueryable() => not working either
            .ProjectTo<PartyDto>(_mapper.ConfigurationProvider)
            .PaginatedListAsync(request.PageNumber, request.PageSize);

The mapping

... code
profile.CreateMap<Party, PartyDto>()
            .ForMember(d => d.FullName, opt => opt.MapFrom(s => MapHelpers.GetPartyFullName(s)));
... more code

Any help would be appreciated.


Solution

  • As you are using .ProjectTo extension automapper will translate it to select operation.

    According to docs: The .ProjectTo<OrderLineDTO>() will tell AutoMapper’s mapping engine to emit a select clause to the IQueryable....

    So most likely mongo db query translator just does not support your MapHelpers.GetPartyFullName function. Try to rewrite your mapping directly in the .MapFrom(...) call.