Skip to content

Commit 4a994dc

Browse files
committed
fix #11 map to nullable enum
1 parent d7d5900 commit 4a994dc

File tree

3 files changed

+35
-4
lines changed

3 files changed

+35
-4
lines changed

src/Mapster.Tests/WhenMappingEnums.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,38 @@ public void String_Is_Mapped_To_Enum()
8787
dto.Department.ShouldBe(Departments.IT);
8888
}
8989

90+
[TestMethod]
91+
public void String_Is_Mapped_To_Nullable_Enum()
92+
{
93+
var department = Departments.IT.ToString();
94+
var value = TypeAdapter.Adapt<string, Departments?>(department);
95+
value.ShouldBe(Departments.IT);
96+
}
97+
98+
[TestMethod]
99+
public void Null_String_Is_Mapped_To_Nullable_Enum()
100+
{
101+
string department = null;
102+
var value = TypeAdapter.Adapt<string, Departments?>(department);
103+
value.ShouldBeNull();
104+
}
105+
106+
[TestMethod]
107+
public void Nullable_Enum_Is_Mapped_To_String()
108+
{
109+
var department = Departments.IT;
110+
var value = TypeAdapter.Adapt<Departments?, string>(department);
111+
value.ShouldBe(Departments.IT.ToString());
112+
}
113+
114+
[TestMethod]
115+
public void Null_Nullable_Enum_Is_Mapped_To_String()
116+
{
117+
Departments? department = null;
118+
var value = TypeAdapter.Adapt<Departments?, string>(department);
119+
value.ShouldBeNull();
120+
}
121+
90122
[TestMethod]
91123
public void Enum_Is_Mapped_To_Enum()
92124
{

src/Mapster/Adapters/EnumAdapter.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ internal class EnumAdapter : PrimitiveAdapter
1212

1313
protected override bool CanMap(PreCompileArgument arg)
1414
{
15-
return arg.SourceType.GetTypeInfo().IsEnum || arg.DestinationType.GetTypeInfo().IsEnum;
15+
return arg.SourceType.UnwrapNullable().GetTypeInfo().IsEnum
16+
|| arg.DestinationType.UnwrapNullable().GetTypeInfo().IsEnum;
1617
}
1718

1819
protected override Expression ConvertType(Expression source, Type destinationType, CompileArgument arg)

src/Mapster/Mapster.NetCore.csproj

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,15 @@
2222
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
2323
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
2424
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
25-
<Version>3.1.4</Version>
25+
<Version>3.1.5</Version>
2626
<RootNamespace>Mapster</RootNamespace>
2727
</PropertyGroup>
2828

2929
<ItemGroup Condition=" '$(TargetFramework)' == 'net40' ">
30-
<Reference Include="System" />
3130
<Reference Include="Microsoft.CSharp" />
3231
</ItemGroup>
3332

3433
<ItemGroup Condition=" '$(TargetFramework)' == 'net45' ">
35-
<Reference Include="System" />
3634
<Reference Include="Microsoft.CSharp" />
3735
</ItemGroup>
3836

0 commit comments

Comments
 (0)