0

Im trying to execute a mongodb query with projection and I want to use automapper to map the model and the DTO.

Im using mongodbdriver 2.23

public class MachineOperationModel
{
    public ObjectId Id { get; set; }
    public EMachineStatus MachineStatus { get; set; }
    public EDevStatus DevStatus { get; set; }
    public TimeSpan StartTime { get; set; }
    public TimeSpan EndTime { get; set; }
}
public class MachineOperationDto
{
    public ObjectId Id { get; set; }
    public TimeSpan StartTime { get; set; }
    public TimeSpan EndTime { get; set; }
}
public async Task<IEnumerable<MachineOperationDto>?> Teste()
{
    var proj = Builders<MachineOperation>.Projection.Expression(m => _mapper.Map<MachineOperationDto>(m));

    var teste2 = await _collection
        .Find(Builders<MachineOperation>.Filter.Empty)
        .Project(proj)
        .ToListAsync();
}

When I try to run the projection, I receive the following error:

Expression not supported: value(AutoMapper.Mapper).Map(m).

Both classes are properly mapped with AutoMapper

private void MachineOperationMap()
{
    CreateMap<MachineOperation, MachineOperationDto>()
        .ReverseMap();
}

I've read a lot of stackoverflow questions but no answer has solved my problem

3
  • 2
    The project expression will be evaluated server-side, I don't think AutoMapper is available on the server. For an example, see mongodb.com/docs/drivers/csharp/current/fundamentals/builders/… Commented Feb 8, 2024 at 18:29
  • 1
    Try ProjectTo instead. Commented Feb 8, 2024 at 19:31
  • 1
    you should remember that linq expression you provide should be transformed in mongo query language (MQL), in this case driver does nothing about method you provided and therefore can't translate it Commented Feb 8, 2024 at 20:47

1 Answer 1

2

the projection is going to happen in mongo and auto mapper is not available in mongo engine. you can use below code :

Builders<MachineOperation>.Projection.As<MachineOperationDto>()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.