Skip to content

Commit

Permalink
Allow custom type handlers for Enums.
Browse files Browse the repository at this point in the history
  • Loading branch information
otac0n committed May 11, 2015
1 parent 808c270 commit 817fa95
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 deletions Dapper NET40/SqlMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -898,7 +898,7 @@ internal static DbType LookupDbType(Type type, string name, bool demand, out ITy
handler = null;
var nullUnderlyingType = Nullable.GetUnderlyingType(type);
if (nullUnderlyingType != null) type = nullUnderlyingType;
if (type.IsEnum() && !typeMap.ContainsKey(type))
if (type.IsEnum() && !typeMap.ContainsKey(type) && !typeHandlers.ContainsKey(type))
{
type = Enum.GetUnderlyingType(type);
}
Expand Down Expand Up @@ -3495,6 +3495,15 @@ private static Func<IDataReader, object> GetStructDeserializer(Type type, Type e
}
#pragma warning restore 618

ITypeHandler handler;
if(typeHandlers.TryGetValue(type, out handler))
{
return r =>
{
var val = r.GetValue(index);
return val is DBNull ? null : handler.Parse(type, val);
};
}
if (effectiveType.IsEnum())
{ // assume the value is returned as the correct type (int/byte/etc), but box back to the typed enum
return r =>
Expand All @@ -3507,15 +3516,6 @@ private static Func<IDataReader, object> GetStructDeserializer(Type type, Type e
return val is DBNull ? null : Enum.ToObject(effectiveType, val);
};
}
ITypeHandler handler;
if(typeHandlers.TryGetValue(type, out handler))
{
return r =>
{
var val = r.GetValue(index);
return val is DBNull ? null : handler.Parse(type, val);
};
}
return r =>
{
var val = r.GetValue(index);
Expand All @@ -3529,6 +3529,11 @@ private static T Parse<T>(object value)
if (value is T) return (T)value;
var type = typeof(T);
type = Nullable.GetUnderlyingType(type) ?? type;
ITypeHandler handler;
if (typeHandlers.TryGetValue(type, out handler))
{
return (T)handler.Parse(type, value);
}
if (type.IsEnum())
{
if (value is float || value is double || value is decimal)
Expand All @@ -3537,11 +3542,6 @@ private static T Parse<T>(object value)
}
return (T)Enum.ToObject(type, value);
}
ITypeHandler handler;
if (typeHandlers.TryGetValue(type, out handler))
{
return (T)handler.Parse(type, value);
}
return (T)Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}

Expand Down

0 comments on commit 817fa95

Please sign in to comment.