-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSqlMapper.TypeHandler.cs
86 lines (78 loc) · 3.19 KB
/
SqlMapper.TypeHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Data;
namespace Dapper
{
public static partial class SqlMapper
{
/// <summary>
/// Base-class for simple type-handlers
/// </summary>
/// <typeparam name="T">This <see cref="Type"/> this handler is for.</typeparam>
public abstract class TypeHandler<T> : ITypeHandler
{
/// <summary>
/// Assign the value of a parameter before a command executes
/// </summary>
/// <param name="parameter">The parameter to configure</param>
/// <param name="value">Parameter value</param>
public abstract void SetValue(IDbDataParameter parameter, T value);
/// <summary>
/// Parse a database value back to a typed value
/// </summary>
/// <param name="value">The value from the database</param>
/// <returns>The typed value</returns>
public abstract T Parse(object value);
void ITypeHandler.SetValue(IDbDataParameter parameter, object value)
{
if (value is DBNull)
{
parameter.Value = value;
}
else
{
SetValue(parameter, (T)value);
}
}
object ITypeHandler.Parse(Type destinationType, object value)
{
return Parse(value);
}
}
/// <summary>
/// Base-class for simple type-handlers that are based around strings
/// </summary>
/// <typeparam name="T">This <see cref="Type"/> this handler is for.</typeparam>
public abstract class StringTypeHandler<T> : TypeHandler<T>
{
/// <summary>
/// Parse a string into the expected type (the string will never be null)
/// </summary>
/// <param name="xml">The string to parse.</param>
protected abstract T Parse(string xml);
/// <summary>
/// Format an instance into a string (the instance will never be null)
/// </summary>
/// <param name="xml">The string to format.</param>
protected abstract string Format(T xml);
/// <summary>
/// Assign the value of a parameter before a command executes
/// </summary>
/// <param name="parameter">The parameter to configure</param>
/// <param name="value">Parameter value</param>
public override void SetValue(IDbDataParameter parameter, T value)
{
parameter.Value = value == null ? (object)DBNull.Value : Format(value);
}
/// <summary>
/// Parse a database value back to a typed value
/// </summary>
/// <param name="value">The value from the database</param>
/// <returns>The typed value</returns>
public override T Parse(object value)
{
if (value == null || value is DBNull) return default;
return Parse((string)value);
}
}
}
}