Ignore Automapper property

Asked

Viewed 291 times

3

I’m using Automapper version 7. I need to ignore a property that is in the result class and has no source class. As below.

public class Contrato
{
    public string Id{get;set;}
    public string Nome {get;set;}
}

public class ContratoDto
{
    public string Id{get;set;}
    public string Nome {get;set;}
    public string Descricao{get;set;}
}

If I use Mapper as below, it gives me the error that has Uncharted Property.

CreateMap<Contrato, ContratoDto>();
var c = _contratoRepositorio.BuscarContrato(requisicao.CodigoContrato).FirstOrDefault();

Mapper.Map<Contrato, ContratoDto>(c));

Unmapped Property: Description

How can I ignore the property in Dto that does not exist and will not exist within the model?

1 answer

1

You can ignore properties with .ForMember(p => p.Propriedade, x=> x.Ignore())

Thus remaining:

CreateMap<Contrato, ContratoDto>().ForMember(p => p.Descricao, x=> x.Ignore());

In an OR search I found this answer where is given a Solution via extension method, but I never got to test.

Follows the code:

public static IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> map,
    Expression<Func<TDestination, object>> selector)
{
    map.ForMember(selector, config => config.Ignore());
    return map;
}

Mapper.CreateMap<JsonRecord, DatabaseRecord>()
        .Ignore(record => record.Field)
        .Ignore(record => record.AnotherField)
        .Ignore(record => record.Etc);
  • o . Formember(p => p.Property, x=> x.Ignore()) does not work for me. I opened this question precisely because I stress using . Formember and it does not work.

  • Tried with the ForSourceMember?

  • @Can Thiagohenrique explain what didn’t work? I think that in version 7 onwards is not used .Ignore(), but yes .DoNotValidate(), make a test and I can put in more detail

  • @Barbetta tried them both. neither worked.

  • I found the "temporary" solution that for now helped me, but I do not know if it is the correct option. cfg.ValidateInlineMaps = false; in Mapper’s Initialize. In this case it failed to validate everything.

  • @Ricardopunctual this option has not available in my version. It has the same Ignore.

  • @Thiagohenrique the DoNotValidate is available as of version 8, went to confirm :) http://docs.automapper.org/en/stable/8.0-Upgrade-Guide.html

  • @Ricardopunctual good. Thanks Ricardo.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.