-
Notifications
You must be signed in to change notification settings - Fork 420
/
SimpleCRUDAsync.cs
570 lines (496 loc) · 28.8 KB
/
SimpleCRUDAsync.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
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dapper
{
/// <summary>
/// Main class for Dapper.SimpleCRUD extensions
/// </summary>
public static partial class SimpleCRUD
{
/// <summary>
/// <para>By default queries the table matching the class name asynchronously </para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>By default filters on the Id column</para>
/// <para>-Id column name can be overridden by adding an attribute on your primary key property [Key]</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns a single entity by a single id from table T</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="id"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Returns a single entity by a single id from table T.</returns>
public static async Task<T> GetAsync<T>(this IDbConnection connection, object id, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var idProps = GetIdProperties(currenttype).ToList();
if (!idProps.Any())
throw new ArgumentException("Get<T> only supports an entity with a [Key] or Id property");
var name = GetTableName(currenttype);
var sb = new StringBuilder();
sb.Append("Select ");
//create a new empty instance of the type to get the base properties
BuildSelect(sb, GetScaffoldableProperties<T>().ToArray());
sb.AppendFormat(" from {0} where ", name);
for (var i = 0; i < idProps.Count; i++)
{
if (i > 0)
sb.Append(" and ");
sb.AppendFormat("{0} = @{1}", GetColumnName(idProps[i]), idProps[i].Name);
}
var dynParms = new DynamicParameters();
if (idProps.Count == 1)
dynParms.Add("@" + idProps.First().Name, id);
else
{
foreach (var prop in idProps)
dynParms.Add("@" + prop.Name, id.GetType().GetProperty(prop.Name).GetValue(id, null));
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Get<{0}>: {1} with Id: {2}", currenttype, sb, id));
var query = await connection.QueryAsync<T>(sb.ToString(), dynParms, transaction, commandTimeout);
return query.FirstOrDefault();
}
/// <summary>
/// <para>By default queries the table matching the class name asynchronously</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>whereConditions is an anonymous type to filter the results ex: new {Category = 1, SubCategory=2}</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns a list of entities that match where conditions</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="whereConditions"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Gets a list of entities with optional exact match where conditions</returns>
public static Task<IEnumerable<T>> GetListAsync<T>(this IDbConnection connection, object whereConditions, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
var whereprops = GetAllProperties(whereConditions).ToArray();
sb.Append("Select ");
//create a new empty instance of the type to get the base properties
BuildSelect(sb, GetScaffoldableProperties<T>().ToArray());
sb.AppendFormat(" from {0}", name);
if (whereprops.Any())
{
sb.Append(" where ");
BuildWhere<T>(sb, whereprops, whereConditions);
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("GetList<{0}>: {1}", currenttype, sb));
return connection.QueryAsync<T>(sb.ToString(), whereConditions, transaction, commandTimeout);
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>conditions is an SQL where clause and/or order by clause ex: "where name='bob'" or "where age>=@Age"</para>
/// <para>parameters is an anonymous type to pass in named parameter values: new { Age = 15 }</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns a list of entities that match where conditions</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="conditions"></param>
/// <param name="parameters"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Gets a list of entities with optional SQL where conditions</returns>
public static Task<IEnumerable<T>> GetListAsync<T>(this IDbConnection connection, string conditions, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
sb.Append("Select ");
//create a new empty instance of the type to get the base properties
BuildSelect(sb, GetScaffoldableProperties<T>().ToArray());
sb.AppendFormat(" from {0}", name);
sb.Append(" " + conditions);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("GetList<{0}>: {1}", currenttype, sb));
return connection.QueryAsync<T>(sb.ToString(), parameters, transaction, commandTimeout);
}
/// <summary>
/// <para>By default queries the table matching the class name asynchronously</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Returns a list of all entities</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <returns>Gets a list of all entities</returns>
public static Task<IEnumerable<T>> GetListAsync<T>(this IDbConnection connection)
{
return connection.GetListAsync<T>(new { });
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>conditions is an SQL where clause ex: "where name='bob'" or "where age>=@Age" - not required </para>
/// <para>orderby is a column or list of columns to order by ex: "lastname, age desc" - not required - default is by primary key</para>
/// <para>parameters is an anonymous type to pass in named parameter values: new { Age = 15 }</para>
/// <para>Returns a list of entities that match where conditions</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="pageNumber"></param>
/// <param name="rowsPerPage"></param>
/// <param name="conditions"></param>
/// <param name="orderby"></param>
/// <param name="parameters"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Gets a list of entities with optional exact match where conditions</returns>
public static Task<IEnumerable<T>> GetListPagedAsync<T>(this IDbConnection connection, int pageNumber, int rowsPerPage, string conditions, string orderby, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null)
{
if (string.IsNullOrEmpty(_getPagedListSql))
throw new Exception("GetListPage is not supported with the current SQL Dialect");
var currenttype = typeof(T);
var idProps = GetIdProperties(currenttype).ToList();
if (!idProps.Any())
throw new ArgumentException("Entity must have at least one [Key] property");
var name = GetTableName(currenttype);
var sb = new StringBuilder();
var query = _getPagedListSql;
if (string.IsNullOrEmpty(orderby))
{
orderby = GetColumnName(idProps.First());
}
//create a new empty instance of the type to get the base properties
BuildSelect(sb, GetScaffoldableProperties<T>().ToArray());
query = query.Replace("{SelectColumns}", sb.ToString());
query = query.Replace("{TableName}", name);
query = query.Replace("{PageNumber}", pageNumber.ToString());
query = query.Replace("{RowsPerPage}", rowsPerPage.ToString());
query = query.Replace("{OrderBy}", orderby);
query = query.Replace("{WhereClause}", conditions);
query = query.Replace("{Offset}", ((pageNumber - 1) * rowsPerPage).ToString());
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("GetListPaged<{0}>: {1}", currenttype, query));
return connection.QueryAsync<T>(query, parameters, transaction, commandTimeout);
}
/// <summary>
/// <para>Inserts a row into the database asynchronously</para>
/// <para>By default inserts into the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Insert filters out Id column and any columns with the [Key] attribute</para>
/// <para>Properties marked with attribute [Editable(false)] and complex types are ignored</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns the ID (primary key) of the newly inserted record if it is identity using the int? type, otherwise null</para>
/// </summary>
/// <param name="connection"></param>
/// <param name="entityToInsert"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The ID (primary key) of the newly inserted record if it is identity using the int? type, otherwise null</returns>
public static Task<int?> InsertAsync<TEntity>(this IDbConnection connection, TEntity entityToInsert, IDbTransaction transaction = null, int? commandTimeout = null)
{
return InsertAsync<int?, TEntity>(connection, entityToInsert, transaction, commandTimeout);
}
/// <summary>
/// <para>Inserts a row into the database, using ONLY the properties defined by TEntity</para>
/// <para>By default inserts into the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Insert filters out Id column and any columns with the [Key] attribute</para>
/// <para>Properties marked with attribute [Editable(false)] and complex types are ignored</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns the ID (primary key) of the newly inserted record if it is identity using the defined type, otherwise null</para>
/// </summary>
/// <param name="connection"></param>
/// <param name="entityToInsert"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The ID (primary key) of the newly inserted record if it is identity using the defined type, otherwise null</returns>
public static async Task<TKey> InsertAsync<TKey, TEntity>(this IDbConnection connection, TEntity entityToInsert, IDbTransaction transaction = null, int? commandTimeout = null)
{
if (typeof(TEntity).IsInterface) //FallBack to BaseType Generic Method : https://stackoverflow.com/questions/4101784/calling-a-generic-method-with-a-dynamic-type
{
return await (Task<TKey>)typeof(SimpleCRUD)
.GetMethods().Where(methodInfo => methodInfo.Name == nameof(InsertAsync) && methodInfo.GetGenericArguments().Count() == 2).Single()
.MakeGenericMethod(new Type[] { typeof(TKey), entityToInsert.GetType() })
.Invoke(null, new object[] { connection, entityToInsert, transaction, commandTimeout });
}
var idProps = GetIdProperties(entityToInsert).ToList();
if (!idProps.Any())
throw new ArgumentException("Insert<T> only supports an entity with a [Key] or Id property");
var keyHasPredefinedValue = false;
var baseType = typeof(TKey);
var underlyingType = Nullable.GetUnderlyingType(baseType);
var keytype = underlyingType ?? baseType;
if (keytype != typeof(int) && keytype != typeof(uint) && keytype != typeof(long) && keytype != typeof(ulong) && keytype != typeof(short) && keytype != typeof(ushort) && keytype != typeof(Guid) && keytype != typeof(string))
{
throw new Exception("Invalid return type");
}
var name = GetTableName(entityToInsert);
var sb = new StringBuilder();
sb.AppendFormat("insert into {0}", name);
sb.Append(" (");
BuildInsertParameters<TEntity>(sb);
sb.Append(") ");
sb.Append("values");
sb.Append(" (");
BuildInsertValues<TEntity>(sb);
sb.Append(")");
if (keytype == typeof(Guid))
{
var guidvalue = (Guid)idProps.First().GetValue(entityToInsert, null);
if (guidvalue == Guid.Empty)
{
var newguid = SequentialGuid();
idProps.First().SetValue(entityToInsert, newguid, null);
}
else
{
keyHasPredefinedValue = true;
}
}
if ((keytype == typeof(int) || keytype == typeof(long)) && Convert.ToInt64(idProps.First().GetValue(entityToInsert, null)) == 0)
{
sb.Append(";" + _getIdentitySql);
}
else
{
keyHasPredefinedValue = true;
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Insert: {0}", sb));
if (keytype == typeof(Guid) || keyHasPredefinedValue)
{
await connection.ExecuteAsync(sb.ToString(), entityToInsert, transaction, commandTimeout);
return (TKey)idProps.First().GetValue(entityToInsert, null);
}
var r = await connection.QueryAsync(sb.ToString(), entityToInsert, transaction, commandTimeout);
return (TKey)r.First().id;
}
/// <summary>
/// <para>Updates a record or records in the database asynchronously</para>
/// <para>By default updates records in the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Updates records where the Id property and properties with the [Key] attribute match those in the database.</para>
/// <para>Properties marked with attribute [Editable(false)] and complex types are ignored</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns number of rows affected</para>
/// </summary>
/// <param name="connection"></param>
/// <param name="entityToUpdate"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of affected records</returns>
public static async Task<int> UpdateAsync<TEntity>(this IDbConnection connection, TEntity entityToUpdate, IDbTransaction transaction = null, int? commandTimeout = null, System.Threading.CancellationToken? token = null)
{
if (typeof(TEntity).IsInterface) //FallBack to BaseType Generic Method : https://stackoverflow.com/questions/4101784/calling-a-generic-method-with-a-dynamic-type
{
return await(Task<int>)typeof(SimpleCRUD)
.GetMethods().Where(methodInfo => methodInfo.Name == nameof(UpdateAsync) && methodInfo.GetGenericArguments().Count() == 1).Single()
.MakeGenericMethod(new Type[] { entityToUpdate.GetType() })
.Invoke(null, new object[] { connection, entityToUpdate, transaction, commandTimeout, token });
}
var idProps = GetIdProperties(entityToUpdate).ToList();
if (!idProps.Any())
throw new ArgumentException("Entity must have at least one [Key] or Id property");
var name = GetTableName(entityToUpdate);
var sb = new StringBuilder();
sb.AppendFormat("update {0}", name);
sb.AppendFormat(" set ");
BuildUpdateSet(entityToUpdate, sb);
sb.Append(" where ");
BuildWhere<TEntity>(sb, idProps, entityToUpdate);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Update: {0}", sb));
System.Threading.CancellationToken cancelToken = token ?? default(System.Threading.CancellationToken);
return await connection.ExecuteAsync(new CommandDefinition(sb.ToString(), entityToUpdate, transaction, commandTimeout, cancellationToken: cancelToken));
}
/// <summary>
/// <para>Deletes a record or records in the database that match the object passed in asynchronously</para>
/// <para>-By default deletes records in the table matching the class name</para>
/// <para>Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Supports transaction and command timeout</para>
/// <para>Returns the number of records affected</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="entityToDelete"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of records affected</returns>
public static Task<int> DeleteAsync<T>(this IDbConnection connection, T entityToDelete, IDbTransaction transaction = null, int? commandTimeout = null)
{
var idProps = GetIdProperties(entityToDelete).ToList();
if (!idProps.Any())
throw new ArgumentException("Entity must have at least one [Key] or Id property");
var name = GetTableName(entityToDelete);
var sb = new StringBuilder();
sb.AppendFormat("delete from {0}", name);
sb.Append(" where ");
BuildWhere<T>(sb, idProps, entityToDelete);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Delete: {0}", sb));
return connection.ExecuteAsync(sb.ToString(), entityToDelete, transaction, commandTimeout);
}
/// <summary>
/// <para>Deletes a record or records in the database by ID asynchronously</para>
/// <para>By default deletes records in the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Deletes records where the Id property and properties with the [Key] attribute match those in the database</para>
/// <para>The number of records affected</para>
/// <para>Supports transaction and command timeout</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="id"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of records affected</returns>
public static Task<int> DeleteAsync<T>(this IDbConnection connection, object id, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var idProps = GetIdProperties(currenttype).ToList();
if (!idProps.Any())
throw new ArgumentException("Delete<T> only supports an entity with a [Key] or Id property");
var name = GetTableName(currenttype);
var sb = new StringBuilder();
sb.AppendFormat("Delete from {0} where ", name);
for (var i = 0; i < idProps.Count; i++)
{
if (i > 0)
sb.Append(" and ");
sb.AppendFormat("{0} = @{1}", GetColumnName(idProps[i]), idProps[i].Name);
}
var dynParms = new DynamicParameters();
if (idProps.Count == 1)
dynParms.Add("@" + idProps.First().Name, id);
else
{
foreach (var prop in idProps)
dynParms.Add("@" + prop.Name, prop.GetValue(id));
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("Delete<{0}> {1}", currenttype, sb));
return connection.ExecuteAsync(sb.ToString(), dynParms, transaction, commandTimeout);
}
/// <summary>
/// <para>Deletes a list of records in the database</para>
/// <para>By default deletes records in the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Deletes records where that match the where clause</para>
/// <para>whereConditions is an anonymous type to filter the results ex: new {Category = 1, SubCategory=2}</para>
/// <para>The number of records affected</para>
/// <para>Supports transaction and command timeout</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="whereConditions"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of records affected</returns>
public static Task<int> DeleteListAsync<T>(this IDbConnection connection, object whereConditions, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
var whereprops = GetAllProperties(whereConditions).ToArray();
sb.AppendFormat("Delete from {0}", name);
if (whereprops.Any())
{
sb.Append(" where ");
BuildWhere<T>(sb, whereprops);
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("DeleteList<{0}> {1}", currenttype, sb));
return connection.ExecuteAsync(sb.ToString(), whereConditions, transaction, commandTimeout);
}
/// <summary>
/// <para>Deletes a list of records in the database</para>
/// <para>By default deletes records in the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Deletes records where that match the where clause</para>
/// <para>conditions is an SQL where clause ex: "where name='bob'" or "where age>=@Age"</para>
/// <para>parameters is an anonymous type to pass in named parameter values: new { Age = 15 }</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="conditions"></param>
/// <param name="parameters"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>The number of records affected</returns>
public static Task<int> DeleteListAsync<T>(this IDbConnection connection, string conditions, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null)
{
if (string.IsNullOrEmpty(conditions))
throw new ArgumentException("DeleteList<T> requires a where clause");
if (!conditions.ToLower().Contains("where"))
throw new ArgumentException("DeleteList<T> requires a where clause and must contain the WHERE keyword");
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
sb.AppendFormat("Delete from {0}", name);
sb.Append(" " + conditions);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("DeleteList<{0}> {1}", currenttype, sb));
return connection.ExecuteAsync(sb.ToString(), parameters, transaction, commandTimeout);
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>conditions is an SQL where clause ex: "where name='bob'" or "where age>=@Age" - not required </para>
/// <para>parameters is an anonymous type to pass in named parameter values: new { Age = 15 }</para>
/// <para>Supports transaction and command timeout</para>
/// /// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="conditions"></param>
/// <param name="parameters"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Returns a count of records.</returns>
public static Task<int> RecordCountAsync<T>(this IDbConnection connection, string conditions = "", object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
sb.Append("Select count(1)");
sb.AppendFormat(" from {0}", name);
sb.Append(" " + conditions);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("RecordCount<{0}>: {1}", currenttype, sb));
return connection.ExecuteScalarAsync<int>(sb.ToString(), parameters, transaction, commandTimeout);
}
/// <summary>
/// <para>By default queries the table matching the class name</para>
/// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para>
/// <para>Returns a number of records entity by a single id from table T</para>
/// <para>Supports transaction and command timeout</para>
/// <para>whereConditions is an anonymous type to filter the results ex: new {Category = 1, SubCategory=2}</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connection"></param>
/// <param name="whereConditions"></param>
/// <param name="transaction"></param>
/// <param name="commandTimeout"></param>
/// <returns>Returns a count of records.</returns>
public static Task<int> RecordCountAsync<T>(this IDbConnection connection, object whereConditions, IDbTransaction transaction = null, int? commandTimeout = null)
{
var currenttype = typeof(T);
var name = GetTableName(currenttype);
var sb = new StringBuilder();
var whereprops = GetAllProperties(whereConditions).ToArray();
sb.Append("Select count(1)");
sb.AppendFormat(" from {0}", name);
if (whereprops.Any())
{
sb.Append(" where ");
BuildWhere<T>(sb, whereprops);
}
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("RecordCount<{0}>: {1}", currenttype, sb));
return connection.ExecuteScalarAsync<int>(sb.ToString(), whereConditions, transaction, commandTimeout);
}
}
}