Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

374
Visualizações
How to map object with custom class property that returns object with null property values instead of returning null using Automapper

I have these classes

public class SemModel
{
    public int SemId {get; set}
    public string AreaId {get; set}
    public string Longitude {get; set}
    public string Latitude {get; set}
}

public class SemDto 
{
    public int SemId {get; set}
    public AreaDto Area {get; set}
}

public class AreaDto 
{
    public string AreaId {get; set}
    public string Longitude {get; set}
    public string Latitude {get; set}
}

I want to be able to map SemModel to SemDto wherein if AreaId, Longitude and Latitude are null SemDto.Area is instatiated with AreaId, Longitude and Latitude properties having null value.

Actual output is that I have a SemDto where Area property is null

this is the mapping I have

CreateMap<SemModel, SemDto>()
    .ForMember(dest => dest.Area, opt => opt.MapFrom(src => new AreaDto
             {
                 AreaId = src.AreaId,
                 Longitude = src.Longitude,
                 Latitude = src.Latitude
             }));

Given:

new SemModel(){SemId =1, AreaId =null, Longitude=null, Latitude=null}

Expected Output:

new SemDto(){SemId = 1, Area = new Area(){ AreaId =null, Longitude =null, Latitude =null}}

Actual Output:

new SemDto(){SemId = 1, Area = null}

Another Attempt 1

.ForPath(dest => dest.Area.AreaId, opt => opt.MapFrom(src => src.AreaId))
.ForPath(dest => dest.Area.Longitude, opt => opt.MapFrom(src => src.Longitude))
.ForPath(dest => dest.Area.Latitude, opt => opt.MapFrom(src => src.Latitude));

Still no luck. Welp!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

    cfg.CreateMap<SemDto, SemModel>().IncludeMembers(s=>s.Area).ReverseMap();
    cfg.CreateMap<AreaDto, SemModel>().ForMember(d=>d.SemId, o=>o.Ignore()).ReverseMap();

It uses unflattening. ForPath works too.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda