-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMapExtension.cs
More file actions
169 lines (145 loc) · 6.86 KB
/
Copy pathMapExtension.cs
File metadata and controls
169 lines (145 loc) · 6.86 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using DataDrain.Caching;
namespace DataDrain.Mapping
{
internal static class Map
{
private static readonly CachingMannager Cache = new CachingMannager(new TimeSpan(0, 0, 5, 0));
/// <summary>
/// Mapeia os campos do DataTable para o objeto alvo
/// </summary>
/// <typeparam name="T">Objeto a ser mapeado</typeparam>
/// <param name="dt">dados a serem mapeados</param>
/// <returns>Lista de objetos mapeados</returns>
public static List<T> MapToEntities<T>(this DataTable dt) where T : class, new()
{
var dr = dt.CreateDataReader();
return dr.MapToEntities<T>();
}
/// <summary>
/// Mapeia os campos do DataView para o objeto alvo
/// </summary>
/// <typeparam name="T">Objeto a ser mapeado</typeparam>
/// <param name="dv">dados a serem mapeados</param>
/// <returns>Lista de objetos mapeados</returns>
public static List<T> MapToEntities<T>(this DataView dv) where T : class, new()
{
var dt = dv.ToTable("Tabela");
return dt.MapToEntities<T>();
}
/// <summary>
/// Mapeia os campos do dataReader para o objeto alvo
/// </summary>
/// <typeparam name="T">Objeto a ser mapeado</typeparam>
/// <param name="dr">dados a serem mapeados</param>
/// <returns>Lista de objetos mapeados</returns>
public static List<T> MapToEntities<T>(this IDataReader dr) where T : class ,new()
{
try
{
var listaNovosObjetos = new List<T>();
var camposValidos = RetornaMapObjeto<T>(dr);
var setters = RetornaSetters<T>(camposValidos);
while (dr.Read())
{
var novoObjeto = new T();
foreach (var p in camposValidos)
{
var valorDr = dr[p.Name];
var setter = setters[p.Name];
if (valorDr != DBNull.Value)
{
if (valorDr is TimeSpan && p.PropertyType == typeof(DateTime))
{
setter(novoObjeto, Convert.ChangeType(valorDr.ToString(), p.PropertyType, System.Globalization.CultureInfo.InvariantCulture));
}
else if (valorDr is byte[] && p.PropertyType == typeof(string))
{
setter(novoObjeto, Convert.ChangeType(System.Text.Encoding.Default.GetString((byte[])valorDr), p.PropertyType, System.Globalization.CultureInfo.InvariantCulture));
}
else if (valorDr is Guid && p.PropertyType == typeof(string))
{
setter(novoObjeto, Convert.ChangeType(valorDr.ToString(), p.PropertyType, System.Globalization.CultureInfo.InvariantCulture));
}
else if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) && p.PropertyType.GetGenericArguments()[0].IsEnum)
{
setter(novoObjeto, Enum.Parse(p.PropertyType.GetGenericArguments()[0], valorDr.ToString()));
}
else if (!p.PropertyType.IsEnum)
{
setter(novoObjeto, Nullable.GetUnderlyingType(p.PropertyType) != null
? Convert.ChangeType(valorDr, Nullable.GetUnderlyingType(p.PropertyType), System.Globalization.CultureInfo.InvariantCulture)
: Convert.ChangeType(valorDr, p.PropertyType, System.Globalization.CultureInfo.InvariantCulture));
}
else if (p.PropertyType.IsEnum)
{
if (valorDr is string)
{
setter(novoObjeto, Enum.Parse(p.PropertyType, valorDr.ToString()));
}
else
{
setter(novoObjeto, Enum.ToObject(p.PropertyType, valorDr));
}
}
}
else
{
if ((p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
setter(novoObjeto, null);
}
else
{
setter(novoObjeto, !p.PropertyType.IsValueType
? null
: Activator.CreateInstance(p.PropertyType));
}
}
}
listaNovosObjetos.Add(novoObjeto);
}
return listaNovosObjetos;
}
catch
{
throw new Exception();
}
}
private static Dictionary<string, Action<T, object>> RetornaSetters<T>(IEnumerable<PropertyInfo> camposValidos)
{
var map = Cache.Recuperar<Dictionary<string, Dictionary<string, Action<T, object>>>>(typeof(T).FullName).Value ?? new Dictionary<string, Dictionary<string, Action<T, object>>>();
var mapObjAtual = camposValidos.ToDictionary(camposValido => camposValido.Name, FastInvoke.BuildUntypedSetter<T>);
if (map.ContainsKey(typeof(T).FullName))
{
return map[typeof(T).FullName];
}
map.Add(typeof(T).FullName, mapObjAtual);
Cache.Adicionar(typeof(T).FullName, map);
return mapObjAtual;
}
private static List<PropertyInfo> RetornaMapObjeto<T>(IDataRecord dr) where T : new()
{
if (dr != null)
{
return typeof(T).GetProperties().Where(p => p.CanWrite && dr.HasColumn(p.Name)).ToList();
}
throw new ArgumentNullException("dr", "DataReader não pode ser nulo");
}
private static bool HasColumn(this IDataRecord dr, string columnName)
{
for (int i = 0; i < dr.FieldCount; i++)
{
if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
}
}