-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataTableCreator.cs
48 lines (39 loc) · 1.42 KB
/
DataTableCreator.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
using CompleteSQL.Mapping;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace CompleteSQL
{
public class DataTableCreator
{
public DataTable Create<TSource>(IEnumerable<TSource> dataSource, string targetTable) where TSource: class
{
DataTableSchemaCreator schemaCreator = new DataTableSchemaCreator();
DataTableSchema schema = schemaCreator.CreateSchema<TSource>(targetTable);
return Create(dataSource, schema);
}
public DataTable Create<TSource>(IEnumerable<TSource> dataSource, DataTableSchema schema) where TSource : class
{
DataTable dt = new DataTable(schema.TableName);
DataColumn dc;
foreach (DataColumnSchema cSchema in schema.Columns)
{
dc = dt.Columns.Add(cSchema.Name, cSchema.Type);
dc.AllowDBNull = cSchema.AllowDbNull;
}
PropertyInfo[] props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
DataRow dr;
foreach (TSource item in dataSource)
{
dr = dt.NewRow();
foreach (PropertyInfo prop in props)
{
dr[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
}
dt.Rows.Add(dr);
}
return dt;
}
}
}