-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlQueryExtensions.cs
More file actions
188 lines (161 loc) · 6.41 KB
/
Copy pathSqlQueryExtensions.cs
File metadata and controls
188 lines (161 loc) · 6.41 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Common;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EFCore.UnitOfWork
{
internal static class SqlQueryExtensions
{
public static async Task<List<T>> GetFromQueryAsync<T>(
this DbContext dbContext,
string sql,
IEnumerable<object> parameters,
CancellationToken cancellationToken = default)
{
if (dbContext == null)
{
throw new ArgumentNullException(nameof(dbContext));
}
if (string.IsNullOrWhiteSpace(sql))
{
throw new ArgumentNullException(nameof(sql));
}
using DbCommand command = dbContext.Database.GetDbConnection().CreateCommand();
command.CommandText = sql;
if (parameters != null)
{
int index = 0;
foreach (object item in parameters)
{
DbParameter dbParameter = command.CreateParameter();
dbParameter.ParameterName = "@p" + index;
dbParameter.Value = item;
command.Parameters.Add(dbParameter);
index++;
}
}
await dbContext.Database.OpenConnectionAsync(cancellationToken);
using DbDataReader result = await command.ExecuteReaderAsync(cancellationToken);
List<T> list = new List<T>();
T obj = default;
while (result.Read())
{
if (!(typeof(T).IsPrimitive || typeof(T).Equals(typeof(string))))
{
obj = Activator.CreateInstance<T>();
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
if (!Equals(result[prop.Name], DBNull.Value))
{
prop.SetValue(obj, result[prop.Name], null);
}
}
list.Add(obj);
}
else
{
obj = (T)Convert.ChangeType(result[0], typeof(T), CultureInfo.InvariantCulture);
list.Add(obj);
}
}
return list;
}
private static async Task<List<T>> GetFromQueryAsync2<T>(
this DbContext dbContext,
string sql,
IEnumerable<object> parameters,
CancellationToken cancellationToken = default)
{
RelationalDataReader relationalDataReader = await dbContext.ExecuteSqlQueryAsync(sql, parameters, cancellationToken);
using DbDataReader dr = relationalDataReader.DbDataReader;
List<T> list = new List<T>();
T t = default;
while (dr.Read())
{
if (!(typeof(T).IsPrimitive || typeof(T).Equals(typeof(string))))
{
PropertyInfo[] props = typeof(T).GetProperties();
IEnumerable<string> actualNames = dr.GetColumnSchema().Select(o => o.ColumnName);
for (int i = 0; i < props.Length; ++i)
{
PropertyInfo pi = props[i];
if (!pi.CanWrite)
{
continue;
}
ColumnAttribute ca = pi.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute;
string name = ca?.Name ?? pi.Name;
if (pi == null)
{
continue;
}
if (!actualNames.Contains(name))
{
continue;
}
object value = dr[name];
Type pt = pi.DeclaringType;
bool nullable = pt.GetTypeInfo().IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>);
if (value == DBNull.Value)
{
value = null;
}
if (value == null && pt.GetTypeInfo().IsValueType && !nullable)
{
value = Activator.CreateInstance(pt);
}
pi.SetValue(t, value);
}
list.Add(t);
}
else
{
t = (T)Convert.ChangeType(dr[0], typeof(T), CultureInfo.InvariantCulture);
list.Add(t);
}
}
return list;
}
private static async Task<RelationalDataReader> ExecuteSqlQueryAsync(
this DbContext dbContext,
string sql,
IEnumerable<object> parameters,
CancellationToken cancellationToken = default)
{
if (dbContext == null)
{
throw new ArgumentNullException(nameof(dbContext));
}
if (string.IsNullOrWhiteSpace(sql))
{
throw new ArgumentNullException(nameof(sql));
}
IConcurrencyDetector concurrencyDetector = dbContext.GetService<IConcurrencyDetector>();
using (concurrencyDetector.EnterCriticalSection())
{
RawSqlCommand rawSqlCommand = dbContext
.GetService<IRawSqlCommandBuilder>()
.Build(sql, parameters);
RelationalCommandParameterObject paramObject = new RelationalCommandParameterObject(
dbContext.GetService<IRelationalConnection>(),
rawSqlCommand.ParameterValues,
null,
null,
null);
RelationalDataReader relationalDataReader = await rawSqlCommand
.RelationalCommand
.ExecuteReaderAsync(paramObject, cancellationToken);
return relationalDataReader;
}
}
}
}