-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectDataReader.cs
627 lines (512 loc) · 21.8 KB
/
ObjectDataReader.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//===============================================================================
// Copyright © 2008 Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
//
//This code lives here: https://github.com/dbrownems/ObjectDataReader
//Please visit for comments, issues and updates
//
namespace Microsoft.Samples.ObjectDataReader
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
/// <summary>
/// The ObjectDataReader wraps a collection of CLR objects in a DbDataReader.
/// Only "scalar" properties are projected.
///
/// This is useful for doing high-speed data loads with SqlBulkCopy, and copying collections
/// of entities ot a DataTable for use with SQL Server Table-Valued parameters, or for interop
/// with older ADO.NET applciations.
///
/// For explicit control over the fields projected by the DataReader, just wrap your collection
/// of entities in a anonymous type projection before wrapping it in an ObjectDataReader.
///
/// Instead of
/// IEnumerable<Order> orders;
/// ...
/// IDataReader dr = orders.AsDataReader();
///
/// do
/// IEnumerable<Order> orders;
/// ...
/// var q = from o in orders
/// select new
/// {
/// ID=o.ID,
/// ShipDate=o.ShipDate,
/// ProductName=o.Product.Name,
/// ...
/// }
/// IDataReader dr = q.AsDataReader();
///
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class ObjectDataReader<T> : DbDataReader, IDataReader
{
readonly IEnumerator<T> enumerator;
T current;
bool closed = false;
/// <summary>
/// Metadata cache collections. Initialized lazilly by the constructor.
/// </summary>
//basic list of scalar attributes for T
static List<Attribute> scalarAttributes;
/// <summary>
/// Metadata for this insance. Composed from metadata cache in the constructor.
/// </summary>
readonly List<Attribute> attributes;
#region Attribute inner type
/// <summary>
/// The Attribute is responsible for projecting a single property into a DataReader column.
/// </summary>
private class Attribute
{
//PropertyInfo propertyInfo;
public readonly Type Type;
public readonly string Name;
readonly Func<T, object> ValueAccessor;
/// <summary>
/// Uses Lamda expressions to create a Func<T,object> that invokes the given property getter.
/// The property value will be extracted and cast to type TProperty
/// </summary>
/// <typeparam name="TObject">The type of the object declaring the property.</typeparam>
/// <typeparam name="TProperty">The type to cast the property value to</typeparam>
/// <param name="pi">PropertyInfo pointing to the property to wrap</param>
/// <returns></returns>
static Func<TObject, TProperty> MakePropertyAccessor<TObject, TProperty>(PropertyInfo pi)
{
ParameterExpression objParam = Expression.Parameter(typeof(TObject), "obj");
MemberExpression typedAccessor = Expression.PropertyOrField(objParam, pi.Name);
UnaryExpression castToObject = Expression.Convert(typedAccessor, typeof(object));
LambdaExpression lambdaExpr = Expression.Lambda<Func<TObject, TProperty>>(castToObject, objParam);
return (Func<TObject, TProperty>)lambdaExpr.Compile();
}
public Attribute(PropertyInfo pi)
{
this.Name = pi.Name;
Type = pi.PropertyType;
ValueAccessor = MakePropertyAccessor<T, object>(pi);
}
public Attribute(string name, Type type, Func<T, object> getValue)
{
this.Name = name;
this.Type = type;
this.ValueAccessor = getValue;
}
public object GetValue(T target)
{
return ValueAccessor(target);
}
}
#endregion
#region Scalar Types
static bool IsScalarType(Type t)
{
return scalarTypes.Contains(t);
}
static readonly HashSet<Type> scalarTypes = LoadScalarTypes();
static HashSet<Type> LoadScalarTypes()
{
HashSet<Type> set = new HashSet<Type>()
{
//reference types
typeof(String),
typeof(Byte[]),
//value types
typeof(Byte),
typeof(Int16),
typeof(Int32),
typeof(Int64),
typeof(Single),
typeof(Double),
typeof(Decimal),
typeof(DateTime),
typeof(Guid),
typeof(Boolean),
typeof(TimeSpan),
//nullable value types
typeof(Byte?),
typeof(Int16?),
typeof(Int32?),
typeof(Int64?),
typeof(Single?),
typeof(Double?),
typeof(Decimal?),
typeof(DateTime?),
typeof(Guid?),
typeof(Boolean?),
typeof(TimeSpan?)
};
return set;
}
#endregion
#region Constructors
public ObjectDataReader(IEnumerable<T> col)
{
this.enumerator = col.GetEnumerator();
//done without a lock, so we risk running twice. These collecitons are static so these collecitons
//only need to be initialized once.
if (scalarAttributes == null)
{
scalarAttributes = DiscoverScalarAttributes(typeof(T));
}
attributes = scalarAttributes;
}
static List<Attribute> DiscoverScalarAttributes(Type thisType)
{
//Not a collection of entities, just an IEnumerable<String> or other scalar type.
//So add just a single Attribute that returns the object itself
if (IsScalarType(thisType))
{
return new List<Attribute> { new Attribute("Value", thisType, t => t) };
}
//find all the scalar properties
var allProperties = (from p in thisType.GetProperties()
where IsScalarType(p.PropertyType)
select p).ToList();
//Look for a constructor with arguments that match the properties on name and type
//(name modulo case, which varies between constructor args and properties in coding convention)
//If such an "ordering constructor" exists, return the properties ordered by the corresponding
//constructor args ordinal position.
//An important instance of an ordering constructor, is that C# anonymous types all have one. So
//this enables a simple convention to specify the order of columns projected by the ObjectDataReader
//by simply building the ObjectDataReader from an anonymous type projection.
//If such a constructor is found, replace allProperties with a collection of properties sorted by constructor order.
foreach (var completeConstructor in from ci in thisType.GetConstructors()
where ci.GetParameters().Count() == allProperties.Count()
select ci)
{
var q = (from cp in completeConstructor.GetParameters()
join p in allProperties
on new { n = cp.Name.ToLower(), t = cp.ParameterType } equals new { n = p.Name.ToLower(), t = p.PropertyType }
select new { cp, p }).ToList();
if (q.Count() == allProperties.Count()) //all constructor parameters matched by name and type to properties
{
//sort all properties by constructor ordinal position
allProperties = (from o in q
orderby o.cp.Position
select o.p).ToList();
break; //stop looking for an ordering consturctor
}
}
var atts = new List<Attribute>(allProperties.Count);
foreach (var p in allProperties)
{
atts.Add(new Attribute(p));
}
return atts;
}
#endregion
#region Utility Methods
static Type nullable_T = typeof(System.Nullable<int>).GetGenericTypeDefinition();
static bool IsNullable(Type t)
{
return (t.IsGenericType
&& t.GetGenericTypeDefinition() == nullable_T);
}
static Type StripNullableType(Type t)
{
return t.GetGenericArguments()[0];
}
#endregion
#region GetSchemaTable
const string shemaTableSchema = @"<?xml version=""1.0"" standalone=""yes""?>
<xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
<xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:MainDataTable=""SchemaTable"" msdata:Locale="""">
<xs:complexType>
<xs:choice minOccurs=""0"" maxOccurs=""unbounded"">
<xs:element name=""SchemaTable"" msdata:Locale="""" msdata:MinimumCapacity=""1"">
<xs:complexType>
<xs:sequence>
<xs:element name=""ColumnName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""ColumnOrdinal"" msdata:ReadOnly=""true"" type=""xs:int"" default=""0"" minOccurs=""0"" />
<xs:element name=""ColumnSize"" msdata:ReadOnly=""true"" type=""xs:int"" minOccurs=""0"" />
<xs:element name=""NumericPrecision"" msdata:ReadOnly=""true"" type=""xs:short"" minOccurs=""0"" />
<xs:element name=""NumericScale"" msdata:ReadOnly=""true"" type=""xs:short"" minOccurs=""0"" />
<xs:element name=""IsUnique"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""IsKey"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""BaseServerName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""BaseCatalogName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""BaseColumnName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""BaseSchemaName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""BaseTableName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""DataType"" msdata:DataType=""System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""AllowDBNull"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""ProviderType"" msdata:ReadOnly=""true"" type=""xs:int"" minOccurs=""0"" />
<xs:element name=""IsAliased"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""IsExpression"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""IsIdentity"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""IsAutoIncrement"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""IsRowVersion"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""IsHidden"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""IsLong"" msdata:ReadOnly=""true"" type=""xs:boolean"" default=""false"" minOccurs=""0"" />
<xs:element name=""IsReadOnly"" msdata:ReadOnly=""true"" type=""xs:boolean"" minOccurs=""0"" />
<xs:element name=""ProviderSpecificDataType"" msdata:DataType=""System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""DataTypeName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""XmlSchemaCollectionDatabase"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""XmlSchemaCollectionOwningSchema"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""XmlSchemaCollectionName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""UdtAssemblyQualifiedName"" msdata:ReadOnly=""true"" type=""xs:string"" minOccurs=""0"" />
<xs:element name=""NonVersionedProviderType"" msdata:ReadOnly=""true"" type=""xs:int"" minOccurs=""0"" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>";
public override DataTable GetSchemaTable()
{
DataSet s = new DataSet();
s.Locale = System.Globalization.CultureInfo.CurrentCulture;
s.ReadXmlSchema(new System.IO.StringReader(shemaTableSchema));
DataTable t = s.Tables[0];
for (int i = 0; i < this.FieldCount; i++)
{
DataRow row = t.NewRow();
row["ColumnName"] = this.GetName(i);
row["ColumnOrdinal"] = i;
Type type = this.GetFieldType(i);
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(System.Nullable<int>).GetGenericTypeDefinition())
{
type = type.GetGenericArguments()[0];
}
row["DataType"] = this.GetFieldType(i);
row["DataTypeName"] = this.GetDataTypeName(i);
row["ColumnSize"] = -1;
t.Rows.Add(row);
}
return t;
}
#endregion
#region IDataReader Members
public override void Close()
{
closed = true;
}
public override int Depth
{
get { return 1; }
}
public override bool IsClosed
{
get { return closed; }
}
public override bool NextResult()
{
return false;
}
int entitiesRead = 0;
public override bool Read()
{
bool rv = enumerator.MoveNext();
if (rv)
{
current = enumerator.Current;
entitiesRead += 1;
}
return rv;
}
public override int RecordsAffected
{
get { return -1; }
}
#endregion
#region IDisposable Members
protected override void Dispose(bool disposing)
{
Close();
base.Dispose(disposing);
}
#endregion
#region IDataRecord Members
public override int FieldCount
{
get
{
return attributes.Count;
}
}
TField GetValue<TField>(int i)
{
TField val = (TField)attributes[i].GetValue(current);
return val;
}
public override bool GetBoolean(int i)
{
return GetValue<bool>(i);
}
public override byte GetByte(int i)
{
return GetValue<byte>(i);
}
public override long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
var buf = GetValue<byte[]>(i);
int bytes = Math.Min(length, buf.Length - (int)fieldOffset);
Buffer.BlockCopy(buf, (int)fieldOffset, buffer, bufferoffset, bytes);
return bytes;
}
public override char GetChar(int i)
{
return GetValue<char>(i);
}
public override long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
//throw new NotImplementedException();
string s = GetValue<string>(i);
int chars = Math.Min(length, s.Length - (int)fieldoffset);
s.CopyTo((int)fieldoffset, buffer, bufferoffset, chars);
return chars;
}
//public override DbDataReader GetData(int i)
//{
// throw new NotImplementedException();
//}
public override string GetDataTypeName(int i)
{
return attributes[i].Type.Name;
}
public override DateTime GetDateTime(int i)
{
return GetValue<DateTime>(i);
}
public override decimal GetDecimal(int i)
{
return GetValue<decimal>(i);
}
public override double GetDouble(int i)
{
return GetValue<double>(i);
}
public override Type GetFieldType(int i)
{
Type t = attributes[i].Type;
if (IsNullable(t))
{
t = StripNullableType(t);
}
return t;
}
public override float GetFloat(int i)
{
return GetValue<float>(i);
}
public override Guid GetGuid(int i)
{
return GetValue<Guid>(i);
}
public override short GetInt16(int i)
{
return GetValue<short>(i);
}
public override int GetInt32(int i)
{
return GetValue<int>(i);
}
public override long GetInt64(int i)
{
return GetValue<long>(i);
}
public override string GetName(int i)
{
Attribute a = attributes[i];
return a.Name;
}
public override int GetOrdinal(string name)
{
for (int i = 0; i < attributes.Count; i++)
{
var a = attributes[i];
if (a.Name == name)
{
return i;
}
}
return -1;
}
public override string GetString(int i)
{
return GetValue<string>(i);
}
public override int GetValues(object[] values)
{
for (int i = 0; i < attributes.Count; i++)
{
values[i] = GetValue(i);
}
return attributes.Count;
}
public override object GetValue(int i)
{
object o = GetValue<object>(i);
if (o == null)
{
return DBNull.Value;
}
return o;
}
public override bool IsDBNull(int i)
{
object o = GetValue<object>(i);
return (o == null);
}
public override object this[string name]
{
get { return GetValue(GetOrdinal(name)); }
}
public override object this[int i]
{
get { return GetValue(i); }
}
#endregion
#region DbDataReader Members
public override System.Collections.IEnumerator GetEnumerator()
{
return this.enumerator;
}
public override bool HasRows
{
get { throw new NotSupportedException(); }
}
#endregion
}
public static class ObjectDataReaderExtensions
{
/// <summary>
/// Wraps the IEnumerable in a DbDataReader, having one column for each "scalar" property of the type T.
/// The collection will be enumerated as the client calls IDataReader.Read().
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <returns></returns>
public static IDataReader AsDataReader<T>(this IEnumerable<T> collection)
{
return new ObjectDataReader<T>(collection);
}
/// <summary>
/// Enumerates the collection and copies the data into a DataTable.
/// </summary>
/// <typeparam name="T">The element type of the collection.</typeparam>
/// <param name="collection">The collection to copy to a DataTable</param>
/// <returns>A DataTable containing the scalar projection of the collection.</returns>
public static DataTable ToDataTable<T>(this IEnumerable<T> collection)
{
DataTable t = new DataTable();
t.Locale = System.Globalization.CultureInfo.CurrentCulture;
t.TableName = typeof(T).Name;
ObjectDataReader<T> dr = new ObjectDataReader<T>(collection);
t.Load(dr);
return t;
}
}
}