Search code examples
c#.netmongodbmongodb-.net-drivermap-projections

C# - Simple MongoDB projection with automapping returning "Expression not supported"


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


Solution

  • 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>()