'Automapper with EnumMapping throws on nullable Enums with unknown value

I have a nullable enum property on the source side and get this property with value 0 instead of NULL. But 0 is not a represented value in the enum so AutoMapper with ConvertUsingEnumMapping throws an exception that the enum can not be mapped. Is there a way to map it to NULL whenever the value is not represented in the source enum? Some way to prevent this runtime error?

public class SomeSourceDto
{
    public SomeSourceEnum? SomeEnum { get; set; }
}

public class SomeDestinationDto
{
    public SomeDestinationEnum? SomeEnum { get; set; }
}

public enum SomeSourceEnum
{
    First = 1
}

public enum SomeDestinationEnum
{
    First = 1
}

Mapping configuration:

CreateMap<SomeSourceDto, SomeDestinationDto>();
CreateMap<SomeSourceEnum, SomeDestinationEnum>().ConvertUsingEnumMapping(opt => opt.MapByName());

Mapping:

var someSourceDto = new SomeSourceDto { SomeEnum = 0 };
Mapper.Map<SomeDestinationDto>(someSourceDto);

Exception:

AutoMapper.AutoMapperMappingException

Error mapping types.

...

Destination Member:

SomeEnum

My current workaround is to apply this before the map:

someSourceDto.SomeEnum = someSourceDto.SomeEnum == 0 ? null : someSourceDto.SomeEnum;

Is there a better way? I can't use ConvertUsingEnumMapping when I make the enum types in the map nullable.

The problem is that this can happen for every enum property so I'm at big risk of runtime errors atm because I have no control over the source side of the data.



Solution 1:[1]

You can work it around like this:

CreateMap<SomeSourceDto, SomeDestinationDto>()
    .ForMember(
        dst => dst.SomeEnum,
        opt => opt.MapFrom(
            src => Enum.IsDefined(typeof(SomeDestinationEnum), src.SomeEnum) 
            ? src.SomeEnum 
            : null));

You can rewrite this to an extension method so you can use it more easily for other DTO's

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guru Stron