diff --git a/Dapper/SqlMapper.Settings.cs b/Dapper/SqlMapper.Settings.cs
index cc71238b2..bcbe3790e 100644
--- a/Dapper/SqlMapper.Settings.cs
+++ b/Dapper/SqlMapper.Settings.cs
@@ -99,6 +99,11 @@ public static void SetDefaults()
/// instead of the original name; for most scenarios, this is ignored since the name is redundant, but "snowflake" requires this.
///
public static bool UseIncrementalPseudoPositionalParameterNames { get; set; }
+
+ ///
+ /// Whether to persist an enum by its name () instead of by its underlying numeric value.
+ ///
+ public static bool PersistEnumsByName { get; set; }
}
}
}
diff --git a/Dapper/SqlMapper.cs b/Dapper/SqlMapper.cs
index ee49c2abd..a481bd318 100644
--- a/Dapper/SqlMapper.cs
+++ b/Dapper/SqlMapper.cs
@@ -369,7 +369,10 @@ public static void SetDbType(IDataParameter parameter, object value)
if (nullUnderlyingType != null) type = nullUnderlyingType;
if (type.IsEnum && !typeMap.ContainsKey(type))
{
- type = Enum.GetUnderlyingType(type);
+ if (Settings.PersistEnumsByName)
+ type = typeof(string);
+ else
+ type = Enum.GetUnderlyingType(type);
}
if (typeMap.TryGetValue(type, out var dbType))
{
@@ -2247,6 +2250,9 @@ public static object SanitizeParameterValue(object value)
if (value == null) return DBNull.Value;
if (value is Enum)
{
+ if (Settings.PersistEnumsByName)
+ return value.ToString();
+
TypeCode typeCode = value is IConvertible convertible
? convertible.GetTypeCode()
: Type.GetTypeCode(Enum.GetUnderlyingType(value.GetType()));
@@ -2611,6 +2617,11 @@ internal static Action CreateParamInfoGenerator(Identity ide
// simplicity, box as Nullable and call SanitizeParameterValue
callSanitize = checkForNull = true;
}
+ else if (Settings.PersistEnumsByName)
+ {
+ // When PersistEnumsByName is true, SanitizeParameterValue calls ToString on an enum value.
+ callSanitize = checkForNull = true;
+ }
else
{
checkForNull = false;
diff --git a/docs/index.md b/docs/index.md
index e93135e95..53247621f 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -24,6 +24,8 @@ Note: to get the latest pre-release build, add ` -Pre` to the end of the command
(note: new PRs will not be merged until they add release note wording here)
+- Add `Settings.PersistEnumsByName`, to support persisting an enum by its name (`Enum.ToString()`) instead of by its underlying value. (#1762 via bfriesen)
+
### 2.0.123
- Parameters can now be re-used on subsequent commands (#952 via jamescrowley)