blob: c4087f8f787867f939994e0fad47bbeba92249a0 (
plain)
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
|
using System;
using System.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Gestor.Infrastructure.Helpers
{
internal static class SqlDataReaderHelper
{
public static bool FieldIsNull(this SqlDataReader rd, string fieldName)
{
return rd.IsDBNull(rd.GetOrdinal(fieldName));
}
public static async Task<bool> FieldIsNullAsync(SqlDataReader rd, string fieldName)
{
return await rd.IsDBNullAsync(rd.GetOrdinal(fieldName));
}
public static T GetFieldValue<T>(this SqlDataReader rd, string fieldName, bool normalizeNull = true, bool transformField = true)
{
Type type = rd[fieldName].GetType();
Type type1 = typeof(T);
if (type == typeof(DBNull))
{
if (normalizeNull && (!type1.IsGenericType || !(type1.GetGenericTypeDefinition() == typeof(Nullable<>))))
{
if (type1 == typeof(int) || type1 == typeof(double) || type1 == typeof(decimal) || type1 == typeof(long))
{
return (T)Convert.ChangeType(0, type1);
}
if (type1 == typeof(DateTime))
{
return (T)Convert.ChangeType(DateTime.MinValue, type1);
}
if (type1 == typeof(bool))
{
return (T)Convert.ChangeType(false, type1);
}
}
return default(T);
}
Type underlyingType = Nullable.GetUnderlyingType(type1) ?? type1;
if (type == underlyingType)
{
return (T)rd[fieldName];
}
if (!transformField)
{
return (T)rd[fieldName];
}
object item = rd[fieldName];
if (underlyingType.IsEnum)
{
item = Enum.Parse(underlyingType, item.ToString());
}
if (type == typeof(string) && underlyingType == typeof(bool))
{
item = (string)item == "1";
}
return (T)Convert.ChangeType(item, underlyingType);
}
}
}
|