Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

373
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!