AutoMapper / AutoMapper.Extensions.ExpressionMapping

MIT License
143 stars 39 forks source link

System.InvalidOperationException No coercion operator is defined #156

Closed Xriuk closed 1 year ago

Xriuk commented 1 year ago

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'.
BlaiseD commented 1 year ago

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