Skip to main content

Enum mappings

An enum mapping can be customized by setting the strategy to use. Apply the MapEnumAttribute and pass the strategy to be used for this enum. It is also possible to set the strategy for the entire mapper via the MapperAttribute. Available strategies:

NameDescription
ByValueMatches enum entries by their values (default)
ByValueCheckDefinedMatches enum entries by their values, checks if the target value is defined
ByNameMatches enum entries by their exact names

The IgnoreCase property allows to opt in for case insensitive mappings (defaults to false).

Applied to all enums mapped inside this mapper.

[Mapper(EnumMappingStrategy = EnumMappingStrategy.ByName, EnumMappingIgnoreCase = true)]
public partial class CarMapper
{
...
}

Manually mapped enum values

To explicitly map enum values the MapEnumValueAttibute can be used. Attribute is only valid on mapping methods with enums as parameters.

[Mapper]
public partial class CarMapper
{
[MapEnum(EnumMappingStrategy.ByName)]
[MapEnumValue(CarFeature.AWD, CarFeatureDto.AllWheelDrive)]
public partial CarFeatureDto MapFeature(CarFeature feature);
}

Ignore enum values

To ignore an enum value the MapperIgnoreSourceValue or MapperIgnoreTargetValue attributes can be used. This is especially useful when applying strict enum mappings.

[Mapper]
public partial class CarMapper
{
[MapperIgnoreSourceValue(Fruit.Apple)]
[MapperIgnoreTargetValue(FruitDto.Pineapple)]
public partial FruitDto Map(Fruit source);
}

Fallback value

To map to a fallback value instead of throwing when encountering an unknown value, the FallbackValue property on the MapEnum attribute can be used.

FallbackValue is supported by ByName and ByValueCheckDefined.

[Mapper]
public partial class CarMapper
{
[MapEnum(EnumMappingStrategy.ByName, FallbackValue = CarFeatureDto.Unknown)]
public partial CarFeatureDto MapFeature(CarFeature feature);
}

Strict enum mappings

To enforce strict enum mappings (all source enum values have to be mapped to a target enum value and all target enum values have to be mapped from a source enum value) set the following two EditorConfig settings (see also analyzer diagnostics):

.editorconfig
[*.cs]
dotnet_diagnostic.RMG037.severity = error # Unmapped target enum value
dotnet_diagnostic.RMG038.severity = error # Unmapped source enum value

One side strict enum member mappings

To enforce strict enum member mappings on only either the source or the target, the RequiredMappingStrategy can be used.

Sets the RequiredMappingStrategy for all methods within the mapper, by default it is Both requiring all members to be mapped. This can be overriden by individual mapping methods using MapperRequiredMappingAttribute.

[Mapper(RequiredMappingStrategy = RequiredMappingStrategy.Source)]
public partial class CarMapper
{
...
}