AutoMapper/AutoMapper.Extensions.ExpressionMapping

System.InvalidOperationException No coercion operator is defined

Xriuk opened this issue · 1 comments

Xriuk commented

I don't know if I'm doing something wrong, here's my setup

public class TestId {
  public int MyId { get; set; }
}

public class TestProduct {
  public TestId? Id { get; set; }
}

public class TestProductDto {
  public int Id { get; set; }
}


void Test(){
  var config = new MapperConfiguration(c => {
    c.CreateMap<TestId, int>()
      .ConvertUsing(i => i.MyId);
    c.CreateMap<TestProduct, TestProductDto>();
  });
  
  config.AssertConfigurationIsValid();
  var mapper = config.CreateMapper();

  Expression<Func<TestProductDto, bool>> expr = x => x.Id == 2;
  var mappedExpression = mapper.MapExpression<Expression<Func<TestProduct, bool>>>(expr);
}

Exception:

No coercion operator is defined between types 'TestId' and 'System.Int32'.

ConvertUsing is not supported for expression mapping .ForPath, ForMember and the "auto mapped" properties are supported.

You probably want the following:

            var config = new MapperConfiguration(c => {
                c.CreateMap<TestProduct, TestProductDto>()
                    .ForMember(d => d.Id, opts => opts.MapFrom(s => s.Id == null ? 0 : s.Id.MyId));
            });