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.
x.Stateis null sox.State.Abbreviationwill throw. Post the actual full exception text. You could avoid the error if you usedx.State?.Abbreviation