-
Notifications
You must be signed in to change notification settings - Fork 39
/
DataMapper.cs
260 lines (219 loc) · 7.66 KB
/
DataMapper.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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#region License
/*
* NReco Data library (http://www.nrecosite.com/)
* Copyright 2016 Vitaliy Fedorchenko
* Distributed under the MIT license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.IO;
namespace NReco.Data {
internal class DataMapper {
internal readonly static DataMapper Instance = new DataMapper();
IDictionary<Type,PocoModelSchema> SchemaCache;
internal DataMapper() {
SchemaCache = new ConcurrentDictionary<Type, PocoModelSchema>();
}
PocoModelSchema InferSchema(Type t) {
var keyCols = new List<ColumnMapping>();
var cols = new List<ColumnMapping>();
foreach (var prop in t.GetProperties()) {
var metadata = CheckSchemaAttributes(prop.GetCustomAttributes());
if (metadata.Item3) // not mapped
continue;
var colMapping = new ColumnMapping(
metadata.Item1 ?? prop.Name, t, prop.Name, prop.PropertyType,
prop.CanRead, prop.CanWrite,
metadata.Item4, metadata.Item5, metadata.Item2);
if (metadata.Item2) // is key
keyCols.Add(colMapping);
cols.Add(colMapping);
}
foreach (var fld in t.GetFields()) {
var metadata = CheckSchemaAttributes(fld.GetCustomAttributes());
if (metadata.Item3) // not mapped
continue;
var colMapping = new ColumnMapping(
metadata.Item1 ?? fld.Name, t, fld.Name, fld.FieldType,
true, true,
metadata.Item4, metadata.Item5, metadata.Item2);
if (metadata.Item2) // is key
keyCols.Add(colMapping);
cols.Add(colMapping);
}
var typeAttrs = t.GetCustomAttributes(true);
var tableAttr = typeAttrs.Where(a=>a is TableAttribute).Select(a=>(TableAttribute)a).FirstOrDefault();
return new PocoModelSchema( ( tableAttr?.Name ) ?? t.Name, cols.ToArray(), keyCols.ToArray(), t );
}
internal PocoModelSchema GetSchema(Type t) {
PocoModelSchema schema = null;
if (!SchemaCache.TryGetValue(t, out schema)) {
schema = InferSchema(t);
SchemaCache[t] = schema;
}
return schema;
}
Tuple<string,bool,bool,bool,bool> CheckSchemaAttributes(IEnumerable<Attribute> attrs) {
bool isNotMapped = false;
bool isKey = false;
bool isDbGenerated = false;
bool isIdentity = false;
string colName = null;
foreach (var attr in attrs) {
if (attr is NotMappedAttribute) {
isNotMapped = true;
break;
} else if (attr is KeyAttribute) {
isKey = true;
} else if (attr is ColumnAttribute) {
var colAttr = (ColumnAttribute)attr;
colName = colAttr.Name;
} else if (attr is DatabaseGeneratedAttribute) {
var dbGenAttr = ((DatabaseGeneratedAttribute)attr);
isDbGenerated = true;
if (dbGenAttr.DatabaseGeneratedOption==DatabaseGeneratedOption.Identity)
isIdentity = true;
}
}
return new Tuple<string,bool,bool,bool,bool>(colName, isKey, isNotMapped, isDbGenerated, isIdentity);
}
internal void MapTo(IDataRecord record, object o, Type type, PocoModelSchema schema) {
for (int i = 0; i < record.FieldCount; i++) {
var fieldName = record.GetName(i);
var colMapping = schema.GetColumnMapping(fieldName);
if (colMapping==null || colMapping.SetVal==null)
continue;
var fieldValue = record.GetValue(i);
if (DataHelper.IsNullOrDBNull(fieldValue)) {
fieldValue = null;
if (Nullable.GetUnderlyingType(colMapping.ValueType) == null && colMapping.ValueType._IsValueType() )
fieldValue = colMapping.DefaultValue;
}
colMapping.SetValue(o, fieldValue);
}
}
internal T MapTo<T>(IDataRecord record) {
return (T)MapTo(record, typeof(T));
}
internal object MapTo(IDataRecord record, Type type) {
var schema = GetSchema(type);
if (schema.CreateModel==null)
throw new ArgumentException($"Type '{type.Name}' does not have a default constructor");
var o = schema.CreateModel();
MapTo(record, o, type, schema);
return o;
}
internal class PocoModelSchema {
internal readonly string TableName;
internal readonly ColumnMapping[] Key;
internal readonly ColumnMapping[] Columns;
internal readonly Type ModelType;
Dictionary<string,ColumnMapping> ColNameMap;
internal Func<object> CreateModel;
internal PocoModelSchema(string tableName, ColumnMapping[] cols, ColumnMapping[] key, Type modelType) {
TableName = tableName;
Columns = cols;
Key = key;
ColNameMap = new Dictionary<string, ColumnMapping>(Columns.Length);
for (int i=0; i<Columns.Length; i++) {
ColNameMap[Columns[i].ColumnName] = Columns[i];
}
ModelType = modelType;
if (modelType.GetConstructor(Type.EmptyTypes)!=null) {
var createExpr = Expression.Lambda<Func<object>>( Expression.New(modelType) );
CreateModel = createExpr.Compile();
}
}
internal ColumnMapping GetColumnMapping(string colName) {
ColumnMapping colMapping = null;
ColNameMap.TryGetValue(colName, out colMapping);
return colMapping;
}
}
internal class ColumnMapping {
internal readonly string ColumnName;
internal readonly Type ValueType;
internal readonly Func<object,object> GetVal;
internal readonly Action<object,object> SetVal;
internal readonly bool IsReadOnly;
internal readonly bool IsIdentity;
internal readonly bool IsKey;
internal object DefaultValue;
readonly Type ConvertToType;
readonly bool IsEnum;
internal ColumnMapping(
string colName, Type t,
string propOrFieldName, Type propOrFieldType,
bool canRead, bool canWrite,
bool isReadOnly, bool isIdentity, bool isKey) {
ColumnName = colName;
ValueType = propOrFieldType;
IsReadOnly = isReadOnly;
IsIdentity = isIdentity;
IsKey = isKey;
DefaultValue = null;
if (ValueType._IsValueType())
DefaultValue = Activator.CreateInstance(ValueType);
ConvertToType = ValueType;
if (Nullable.GetUnderlyingType(ValueType) != null)
ConvertToType = Nullable.GetUnderlyingType(ValueType);
IsEnum = ConvertToType._IsEnum();
// compose get
if (canRead) {
var getParamObj = Expression.Parameter(typeof(object));
var getterExpr = Expression.Lambda<Func<object,object>>(
Expression.Convert(
Expression.PropertyOrField( Expression.Convert(getParamObj,t), propOrFieldName ),
typeof(object)
),
getParamObj
);
GetVal = getterExpr.Compile();
}
// compose set
if (canWrite) {
var setParamObj = Expression.Parameter(typeof(object));
var setParamVal = Expression.Parameter(typeof(object));
var setterExpr = Expression.Lambda<Action<object,object>>(
Expression.Assign(
Expression.PropertyOrField( Expression.Convert(setParamObj,t) , propOrFieldName ),
Expression.Convert(setParamVal, propOrFieldType)
), setParamObj, setParamVal
);
SetVal = setterExpr.Compile();
}
}
internal bool SetValue(object obj, object val) {
if (SetVal==null)
return false;
if (val!=null) {
if (IsEnum) {
val = Enum.Parse(ConvertToType, val.ToString(), true);
} else {
val = Convert.ChangeType(val, ConvertToType );
}
}
SetVal(obj, val);
return true;
}
}
}
}