Search code examples
c#automapper

Automapper not mapping null value


I'm trying to map a nullable property, but the automapper indicates an error in this mapping.

Property: HomeTown Source: Person.NaturalPerson.HomeTown

Destination: PersonDTO.NaturalPersonDTO.HomeTown

When the property is null in the source, the following error occurs:

Mapping types:
Person -> PersonDTO
LogSistemas.Domynus.Application.Core.Entities.Person.Person -> LogSistemas.Domynus.Application.Core.Dto.Person.PersonDTO

Type Map configuration:
Person -> PersonDTO
LogSistemas.Domynus.Application.Core.Entities.Person.Person -> LogSistemas.Domynus.Application.Core.Dto.Person.PersonDTO

Destination Member:
NaturalPerson

 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
NaturalPerson -> NaturalPersonDTO
LogSistemas.Domynus.Application.Core.Entities.Person.NaturalPerson -> LogSistemas.Domynus.Application.Core.Dto.Person.NaturalPersonDTO

Type Map configuration:
NaturalPerson -> NaturalPersonDTO
LogSistemas.Domynus.Application.Core.Entities.Person.NaturalPerson -> LogSistemas.Domynus.Application.Core.Dto.Person.NaturalPersonDTO

Destination Member:
HomeTown

 ---> System.NullReferenceException: Object reference not set to an instance of an object.

Classes

public class NaturalPerson
{
    public NaturalPerson()
    {
        HomeTown = new();
    }

    public City HomeTown { get; set; }
}
public class NaturalPersonDTO
{
    public NaturalPersonDTO()
    {
        HomeTown = new CityDTO();
    }

    public CityDTO HomeTown { get; set; }
}

Mapping config

    CreateMap<Entities.Person.Person, PersonDTO>();
    CreateMap<Entities.Person.NaturalPerson, NaturalPersonDTO>();
    CreateMap<City, CityDTO>()
        .ConvertUsing(x => new CityDTO
        {
            Id = x.Id,
            StateId = x.StateId,
            Name = x.Name,
            State = x.State.Abbreviation,
            Country = x.State.Country.Name
        });

As far as I know, automapper maps null without any problems. I couldn't figure this out.


Solution

  • You can't map your nullable property because your mapper profile specifically says to create new object CityDTO from City. So when City is null, then mapper can't perform what you told him.

    You need to modify your mapping profile to something like this:

    ...
    CreateMap<Entities.Person.NaturalPerson, NaturalPersonDTO>();
    CreateMap<City, CityDTO>()
        .ForPath(dist => dist.State, op => op.MapFrom(src => src.State.Abbreviation))
        .ForPath(dist => dist.Country, op => op.MapFrom(src => src.State.Country.Name));