import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';
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:
Name | Description |
---|---|
ByValue | Matches enum entries by their values (default) |
ByValueCheckDefined | Matches enum entries by their values, checks if the target value is defined |
ByName | Matches 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.
// highlight-start
[Mapper(EnumMappingStrategy = EnumMappingStrategy.ByName, EnumMappingIgnoreCase = true)]
// highlight-end
public partial class CarMapper
{
...
}
Applied to the specific enum mapped by this method. Attribute is only valid on mapping method with enums as parameters.
[Mapper]
public partial class CarMapper
{
// highlight-start
[MapEnum(EnumMappingStrategy.ByName, IgnoreCase = true)]
// highlight-end
public partial CarMakeDto MapMake(CarMake make);
}
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)]
// highlight-start
[MapEnumValue(CarFeature.AWD, CarFeatureDto.AllWheelDrive)]
// highlight-end
public partial CarFeatureDto MapFeature(CarFeature feature);
}
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
{
// highlight-start
[MapEnum(EnumMappingStrategy.ByName, FallbackValue = CarFeatureDto.Unknown)]
// highlight-end
public partial CarFeatureDto MapFeature(CarFeature feature);
}
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):
[*.cs]
dotnet_diagnostic.RMG037.severity = error # Unmapped target enum value
dotnet_diagnostic.RMG038.severity = error # Unmapped source enum value