Skip to content

Commit 2a8faab

Browse files
Fix/prefer typehandlers for enums (#2200)
* Add Settings.PreferTypeHandlersForEnums opt-in flag When enabled, Dapper checks for a registered TypeHandler for enum types before falling back to the default integer boxing behavior. This allows custom enum serialization (e.g. storing enums as strings via TypeHandlers) to work on both reads and writes. Patched locations: - LookupDbType: return DbType.Object with handler when flag is on - CreateParamInfoGenerator: skip integer boxing when handler exists - GetSimpleValueDeserializer: route to TypeHandler before Enum.ToObject - Parse<T>: route to TypeHandler before Enum.ToObject Default is false — zero behavior change for existing users. * Patch IL-emitted type deserializer and add tests - Fix 6th enum-before-handler location in GetTypeDeserializer IL emit, preserving Nullable<T> wrapping for nullable enum properties - Fix em-dash in comment (non-ASCII) - Add two tests: round-trip write+read via StringEnumHandler, and nullable enum with null value * Update SDK version from 10.0.102 to 8.0.100 * Update global.json we have fixed the CI glitch separately --------- Co-authored-by: Marc Gravell <marc.gravell@gmail.com>
1 parent 512f024 commit 2a8faab

5 files changed

Lines changed: 169 additions & 17 deletions

File tree

‎Dapper/PublicAPI.Unshipped.txt‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
1-
#nullable enable
1+
#nullable enable
2+
static Dapper.SqlMapper.Settings.PreferTypeHandlersForEnums.get -> bool
3+
static Dapper.SqlMapper.Settings.PreferTypeHandlersForEnums.set -> void

‎Dapper/SqlMapper.Settings.cs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ static Settings()
6565
public static void SetDefaults()
6666
{
6767
CommandTimeout = null;
68-
ApplyNullValues = PadListExpansions = UseIncrementalPseudoPositionalParameterNames = false;
68+
ApplyNullValues = PadListExpansions = UseIncrementalPseudoPositionalParameterNames = PreferTypeHandlersForEnums = false;
6969
AllowedCommandBehaviors = DefaultAllowedCommandBehaviors;
7070
FetchSize = InListStringSplitCount = -1;
7171
}
@@ -129,6 +129,13 @@ public static long FetchSize
129129
/// </summary>
130130
public static bool SupportLegacyParameterTokens { get; set; } = true;
131131

132+
/// <summary>
133+
/// When true, Dapper checks for a registered TypeHandler for enum types before
134+
/// falling back to the default behavior of sending enums as their underlying integer type.
135+
/// This enables custom enum serialization (e.g. storing enums as strings), while preserving existing behavior.
136+
/// </summary>
137+
public static bool PreferTypeHandlersForEnums { get; set; }
138+
132139
private static long s_FetchSize = -1;
133140
}
134141
}

‎Dapper/SqlMapper.cs‎

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,10 @@ public static void SetDbType(IDataParameter parameter, object value)
465465
if (nullUnderlyingType is not null) type = nullUnderlyingType;
466466
if (type.IsEnum && !typeMap.ContainsKey(type))
467467
{
468+
if (Settings.PreferTypeHandlersForEnums && typeHandlers.TryGetValue(type, out handler))
469+
{
470+
return DbType.Object;
471+
}
468472
type = Enum.GetUnderlyingType(type);
469473
}
470474
if (typeMap.TryGetValue(type, out var mapEntry))
@@ -2755,7 +2759,12 @@ private static bool IsValueTuple(Type? type) => (type?.IsValueType == true
27552759

27562760
if ((nullType ?? propType).IsEnum)
27572761
{
2758-
if (nullType is not null)
2762+
if (handler is not null)
2763+
{
2764+
// TypeHandler registered - box as the enum type, handler does conversion
2765+
checkForNull = nullType is not null;
2766+
}
2767+
else if (nullType is not null)
27592768
{
27602769
// Nullable<SomeEnum>; we want to box as the underlying type; that's just *hard*; for
27612770
// simplicity, box as Nullable<SomeEnum> and call SanitizeParameterValue
@@ -3101,7 +3110,16 @@ private static Func<DbDataReader, object> GetSimpleValueDeserializer(Type type,
31013110
#pragma warning restore 618
31023111

31033112
if (effectiveType.IsEnum)
3104-
{ // assume the value is returned as the correct type (int/byte/etc), but box back to the typed enum
3113+
{
3114+
if (Settings.PreferTypeHandlersForEnums && typeHandlers.TryGetValue(type, out var enumHandler))
3115+
{
3116+
return r =>
3117+
{
3118+
var val = r.GetValue(index);
3119+
return val is DBNull ? null! : enumHandler.Parse(type, val)!;
3120+
};
3121+
}
3122+
// assume the value is returned as the correct type (int/byte/etc), but box back to the typed enum
31053123
return r =>
31063124
{
31073125
var val = r.GetValue(index);
@@ -3164,6 +3182,10 @@ private static T Parse<T>(object? value)
31643182
type = Nullable.GetUnderlyingType(type) ?? type;
31653183
if (type.IsEnum)
31663184
{
3185+
if (Settings.PreferTypeHandlersForEnums && typeHandlers.TryGetValue(type, out ITypeHandler? enumHandler))
3186+
{
3187+
return (T)enumHandler.Parse(type, value)!;
3188+
}
31673189
if (value is float || value is double || value is decimal)
31683190
{
31693191
value = Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture);
@@ -3742,22 +3764,31 @@ private static void LoadReaderValueOrBranchToDBNullLabel(ILGenerator il, int ind
37423764

37433765
if (unboxType.IsEnum)
37443766
{
3745-
Type numericType = Enum.GetUnderlyingType(unboxType);
3746-
if (colType == typeof(string))
3767+
if (Settings.PreferTypeHandlersForEnums && typeHandlers.ContainsKey(unboxType))
37473768
{
3748-
stringEnumLocal ??= il.DeclareLocal(typeof(string));
3749-
il.Emit(OpCodes.Castclass, typeof(string)); // stack is now [...][string]
3750-
il.Emit(OpCodes.Stloc, stringEnumLocal); // stack is now [...]
3751-
il.Emit(OpCodes.Ldtoken, unboxType); // stack is now [...][enum-type-token]
3752-
il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle))!, null);// stack is now [...][enum-type]
3753-
il.Emit(OpCodes.Ldloc, stringEnumLocal); // stack is now [...][enum-type][string]
3754-
il.Emit(OpCodes.Ldc_I4_1); // stack is now [...][enum-type][string][true]
3755-
il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [...][enum-as-object]
3756-
il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [...][typed-value]
3769+
#pragma warning disable 618
3770+
il.EmitCall(OpCodes.Call, typeof(TypeHandlerCache<>).MakeGenericType(unboxType).GetMethod(nameof(TypeHandlerCache<int>.Parse))!, null); // stack is now [...][typed-value]
3771+
#pragma warning restore 618
37573772
}
37583773
else
37593774
{
3760-
FlexibleConvertBoxedFromHeadOfStack(il, colType, unboxType, numericType);
3775+
Type numericType = Enum.GetUnderlyingType(unboxType);
3776+
if (colType == typeof(string))
3777+
{
3778+
stringEnumLocal ??= il.DeclareLocal(typeof(string));
3779+
il.Emit(OpCodes.Castclass, typeof(string)); // stack is now [...][string]
3780+
il.Emit(OpCodes.Stloc, stringEnumLocal); // stack is now [...]
3781+
il.Emit(OpCodes.Ldtoken, unboxType); // stack is now [...][enum-type-token]
3782+
il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle))!, null);// stack is now [...][enum-type]
3783+
il.Emit(OpCodes.Ldloc, stringEnumLocal); // stack is now [...][enum-type][string]
3784+
il.Emit(OpCodes.Ldc_I4_1); // stack is now [...][enum-type][string][true]
3785+
il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [...][enum-as-object]
3786+
il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [...][typed-value]
3787+
}
3788+
else
3789+
{
3790+
FlexibleConvertBoxedFromHeadOfStack(il, colType, unboxType, numericType);
3791+
}
37613792
}
37623793

37633794
if (nullUnderlyingType is not null)

‎global.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@
33
"version": "10.0.102",
44
"rollForward": "latestMajor"
55
}
6-
}
6+
}
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
using System;
2+
using System.Data;
3+
using System.Linq;
4+
using Xunit;
5+
6+
namespace Dapper.Tests
7+
{
8+
[Collection(NonParallelDefinition.Name)]
9+
public sealed class SystemSqlClientPreferTypeHandlersForEnumsTests : PreferTypeHandlersForEnumsTests<SystemSqlClientProvider> { }
10+
#if MSSQLCLIENT
11+
[Collection(NonParallelDefinition.Name)]
12+
public sealed class MicrosoftSqlClientPreferTypeHandlersForEnumsTests : PreferTypeHandlersForEnumsTests<MicrosoftSqlClientProvider> { }
13+
#endif
14+
15+
public abstract class PreferTypeHandlersForEnumsTests<TProvider> : TestBase<TProvider> where TProvider : DatabaseProvider
16+
{
17+
private enum Color
18+
{
19+
Red = 1,
20+
Green = 2,
21+
Blue = 3
22+
}
23+
24+
private class ColorResult
25+
{
26+
public Color Value { get; set; }
27+
}
28+
29+
private class NullableColorResult
30+
{
31+
public Color? Value { get; set; }
32+
}
33+
34+
/// <summary>
35+
/// A TypeHandler that stores enum values as their name strings
36+
/// and parses them back from strings.
37+
/// </summary>
38+
private class StringEnumHandler<TEnum> : SqlMapper.TypeHandler<TEnum> where TEnum : struct, Enum
39+
{
40+
public static readonly StringEnumHandler<TEnum> Instance = new();
41+
public int ParseCallCount;
42+
public int SetValueCallCount;
43+
44+
public override TEnum Parse(object? value)
45+
{
46+
ParseCallCount++;
47+
return (TEnum)Enum.Parse(typeof(TEnum), (string)value!);
48+
}
49+
50+
public override void SetValue(IDbDataParameter parameter, TEnum value)
51+
{
52+
SetValueCallCount++;
53+
parameter.DbType = DbType.AnsiString;
54+
parameter.Value = value.ToString();
55+
}
56+
}
57+
58+
[Fact]
59+
public void EnumTypeHandler_WriteAndRead_UsesHandlerWhenEnabled()
60+
{
61+
var handler = new StringEnumHandler<Color>();
62+
var oldSetting = SqlMapper.Settings.PreferTypeHandlersForEnums;
63+
try
64+
{
65+
SqlMapper.ResetTypeHandlers();
66+
SqlMapper.AddTypeHandler(typeof(Color), handler);
67+
SqlMapper.Settings.PreferTypeHandlersForEnums = true;
68+
SqlMapper.PurgeQueryCache();
69+
70+
// Round-trip: write as string, read back via handler
71+
var result = connection.Query<ColorResult>(
72+
"SELECT @Value AS Value", new { Value = Color.Green }).Single();
73+
74+
Assert.Equal(Color.Green, result.Value);
75+
Assert.True(handler.SetValueCallCount > 0, "SetValue should have been called");
76+
Assert.True(handler.ParseCallCount > 0, "Parse should have been called");
77+
}
78+
finally
79+
{
80+
SqlMapper.Settings.PreferTypeHandlersForEnums = oldSetting;
81+
SqlMapper.ResetTypeHandlers();
82+
SqlMapper.PurgeQueryCache();
83+
}
84+
}
85+
86+
[Fact]
87+
public void EnumTypeHandler_NullableWithNull_ReturnsNull()
88+
{
89+
var handler = new StringEnumHandler<Color>();
90+
var oldSetting = SqlMapper.Settings.PreferTypeHandlersForEnums;
91+
try
92+
{
93+
SqlMapper.ResetTypeHandlers();
94+
SqlMapper.AddTypeHandler(typeof(Color), handler);
95+
SqlMapper.Settings.PreferTypeHandlersForEnums = true;
96+
SqlMapper.PurgeQueryCache();
97+
98+
Color? input = null;
99+
var result = connection.Query<NullableColorResult>(
100+
"SELECT @Value AS Value", new { Value = input }).Single();
101+
102+
Assert.Null(result.Value);
103+
}
104+
finally
105+
{
106+
SqlMapper.Settings.PreferTypeHandlersForEnums = oldSetting;
107+
SqlMapper.ResetTypeHandlers();
108+
SqlMapper.PurgeQueryCache();
109+
}
110+
}
111+
}
112+
}

0 commit comments

Comments
 (0)