-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDotMongoCollection.cs
More file actions
650 lines (582 loc) · 25.1 KB
/
Copy pathDotMongoCollection.cs
File metadata and controls
650 lines (582 loc) · 25.1 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
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using dotMongo.Core.Attributes;
using MongoDB.Bson.Serialization;
using System.Linq.Expressions;
using System.Reflection;
namespace dotMongo.Core
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class DotMongoCollection<T> : IDisposable, IDotMongoCollection<T>
{
/// <summary>
///
/// </summary>
public IMongoCollection<BsonDocument> MongoCollection { get; set; }
/// <summary>
///
/// </summary>
/// <param name="db"></param>
public DotMongoCollection(IMongoDatabase db)
{
var collectionName = typeof(T).GetCustomAttributes(typeof(CollectionName), true).FirstOrDefault() as CollectionName;
if (collectionName != null)
{
MongoCollection = db.GetCollection<BsonDocument>(collectionName.Name);
} else
{
MongoCollection = null;
}
}
/// <summary>
///
/// </summary>
/// <param name="db"></param>
/// <param name="collectionName"></param>
public DotMongoCollection(IMongoDatabase db, string collectionName)
{
MongoCollection = db.GetCollection<BsonDocument>(collectionName);
}
/// <summary>
///
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public async Task<IEnumerable<T>> Where(FilterDefinition<BsonDocument> filter)
{
var items = new List<T>();
using (var cursor = await MongoCollection.FindAsync(filter))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var item in batch)
{
items.Add(BsonSerializer.Deserialize<T>(item));
}
}
}
return items;
}
/// <summary>
///
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<IEnumerable<T>> Where(Expression<Func<T, bool>> expression)
{
var items = new List<T>();
if (IsBinaryExpression(expression))
{
using (var cursor = await MongoCollection.FindAsync(ParseExpression((BinaryExpression)expression.Body)))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var item in batch)
{
items.Add(BsonSerializer.Deserialize<T>(item));
}
}
}
}
return items;
}
/// <summary>
/// Get the first result or null
/// </summary>
/// <param name="filter">MongoDB driver filter definition</param>
/// <returns>T in DotMongoCollection</returns>
public async Task<T> FirstOrDefault(FilterDefinition<BsonDocument> filter)
{
var item = await MongoCollection.Find(filter).FirstOrDefaultAsync();
if (item != null)
{
return BsonSerializer.Deserialize<T>(item);
}
return default(T);
}
/// <summary>
/// Get the first result or null
/// </summary>
/// <param name="expression">Lambda expression</param>
/// <returns>T in DotMongoCollection</returns>
public async Task<T> FirstOrDefault(Expression<Func<T, bool>> expression)
{
if (IsBinaryExpression(expression))
{
var item = await MongoCollection.Find(ParseExpression((BinaryExpression)expression.Body)).FirstOrDefaultAsync();
if (item != null)
{
return BsonSerializer.Deserialize<T>(item);
}
}
return default(T); // return null;
}
/// <summary>
///
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public async Task<T> First(FilterDefinition<BsonDocument> filter)
{
return BsonSerializer.Deserialize<T>(await MongoCollection.Find(filter).FirstAsync());
}
public async Task<T> First(Expression<Func<T, bool>> expression)
{
if (expression.Body is BinaryExpression)
{
return BsonSerializer.Deserialize<T>(await MongoCollection.Find(ParseExpression((BinaryExpression)expression.Body)).FirstAsync());
} else
{
throw new ArgumentException($"Binary expression expected in '{expression.ToString()}'.");
}
}
/// <summary>
///
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public async Task<T> SingleOrDefault(FilterDefinition<BsonDocument> filter)
{
return BsonSerializer.Deserialize<T>(await MongoCollection.Find(filter).SingleOrDefaultAsync());
}
/// <summary>
///
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<T> SingleOrDefault(Expression<Func<T, bool>> expression)
{
if (IsBinaryExpression(expression))
{
var item = await MongoCollection.Find(ParseExpression((BinaryExpression)expression.Body)).SingleOrDefaultAsync();
if (item != null)
{
return BsonSerializer.Deserialize<T>(item);
}
}
return default(T);
}
/// <summary>
///
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public async Task<T> Single(FilterDefinition<BsonDocument> filter)
{
return BsonSerializer.Deserialize<T>(await MongoCollection.Find(filter).SingleAsync());
}
/// <summary>
///
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<T> Single(Expression<Func<T, bool>> expression)
{
if (expression.Body is BinaryExpression)
{
return BsonSerializer.Deserialize<T>(await MongoCollection.Find(ParseExpression((BinaryExpression)expression.Body)).SingleAsync());
}
else
{
throw new ArgumentException($"Binary expression expected in '{expression.ToString()}'.");
}
}
/// <summary>
///
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public async Task Delete(FilterDefinition<BsonDocument> filter)
{
await MongoCollection.DeleteOneAsync(filter);
}
/// <summary>
///
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task Delete(Expression<Func<T, bool>> expression)
{
if (expression.Body is BinaryExpression)
{
await MongoCollection.DeleteOneAsync(ParseExpression((BinaryExpression)expression.Body));
}
else
{
throw new ArgumentException($"Binary expression expected in '{expression.ToString()}'.");
}
}
/// <summary>
///
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public async Task DeleteMany(FilterDefinition<BsonDocument> filter)
{
await MongoCollection.DeleteManyAsync(filter);
}
/// <summary>
///
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task DeleteMany(Expression<Func<T, bool>> expression)
{
if (expression.Body is BinaryExpression)
{
await MongoCollection.DeleteManyAsync(ParseExpression((BinaryExpression)expression.Body));
}
else
{
throw new ArgumentException($"Binary expression expected in '{expression.ToString()}'.");
}
}
/// <summary>
///
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public async Task<long> Count(FilterDefinition<BsonDocument> filter)
{
return await MongoCollection.CountAsync(filter);
}
/// <summary>
///
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public async Task<long> Count(Expression<Func<T, bool>> expression)
{
if (expression.Body is BinaryExpression)
{
return await MongoCollection.CountAsync(ParseExpression((BinaryExpression)expression.Body));
}
else
{
throw new ArgumentException($"Binary expression expected in '{expression.ToString()}'.");
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public async Task<long> Count()
{
return await MongoCollection.CountAsync(new BsonDocument());
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public async Task Insert(T item)
{
await MongoCollection.InsertOneAsync(item.ToBsonDocument());
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
public async Task InsertMany(IEnumerable<T> items)
{
await MongoCollection.InsertManyAsync(items.Select(s => s.ToBsonDocument()));
}
public async Task<UpdateResult> Update(T item)
{
// extract the ObjectId and use it to create the Filter Definition
bool withObjId = false;
var filterName = "";
var filterValue = new ObjectId();
Dictionary<string, object> updateDictionary = new Dictionary<string, object>();
var props = item.GetType().GetProperties();
if (props.Length > 0)
{
foreach (var prop in props)
{
if (prop.PropertyType.Name == "ObjectId")
{
withObjId = true;
// save values to be used for filter builder
filterName = prop.Name.Contains("Id") ? "_id" : prop.Name;
filterValue = new ObjectId(prop.GetValue(item).ToString());
}
else
{
// add to the dictionary for the Update Builder
if (prop.CanWrite)
{
object gotValue = null;
if (prop.GetValue(item) != null)
{
gotValue = ConvertToValue(item, prop);
}
updateDictionary.Add(prop.Name, gotValue);
}
}
}
}
if (withObjId)
{
var update = CreateUpdateDefinition(updateDictionary);
var filter = Builders<BsonDocument>.Filter.Eq(filterName, filterValue);
return await MongoCollection.UpdateOneAsync(filter, update);
}
return null;
}
private object ConvertToValue(T item, PropertyInfo prop)
{
switch (prop.PropertyType.FullName)
{
case "System.String":
return prop.GetValue(item).ToString();
case "System.Boolean":
return Convert.ToBoolean(prop.GetValue(item));
case "System.Int16":
return Convert.ToInt16(prop.GetValue(item));
case "System.Int32":
return Convert.ToInt32(prop.GetValue(item));
case "System.Int64":
return Convert.ToInt64(prop.GetValue(item));
case "System.Decimal":
return Convert.ToDecimal(prop.GetValue(item));
case "System.Single":
return Convert.ToSingle(prop.GetValue(item));
case "System.Double":
return Convert.ToDouble(prop.GetValue(item));
case "System.Byte":
return Convert.ToByte(prop.GetValue(item));
case "System.Char":
return Convert.ToChar(prop.GetValue(item));
case "System.DateTime":
return Convert.ToDateTime(prop.GetValue(item));
case "System.UInt16":
return Convert.ToUInt16(prop.GetValue(item));
case "System.UInt32":
return Convert.ToUInt32(prop.GetValue(item));
case "System.UInt64":
return Convert.ToUInt64(prop.GetValue(item));
}
return null;
}
private UpdateDefinition<BsonDocument> CreateUpdateDefinition(Dictionary<string, object> updateDictionary)
{
// create the Update Builder
var ubuilder = Builders<BsonDocument>.Update;
List<UpdateDefinition<BsonDocument>> updates = new List<UpdateDefinition<BsonDocument>>();
foreach (var update in updateDictionary)
{
updates.Add(ubuilder.Set(update.Key, update.Value));
}
return ubuilder.Combine(updates);
}
private FilterDefinition<BsonDocument> ParseExpression(BinaryExpression binary)
{
if (IsRelationalNode(binary.NodeType)) // evaluating Member.Name = Value (e.g. x.User == "James")
{
ValidateParts(binary);
return binary.Right.Type.Name != "ObjectId"
? BuildFilterDefinition(binary.NodeType, (MemberExpression)binary.Left, (ConstantExpression)binary.Right)
: BuildFilterDefinition(binary.NodeType, (MemberExpression)binary.Left, binary.Right);
} else if (IsLogicalNode(binary.NodeType))
{
ValidateOperands(binary);
return BranchFilterDefinition(binary.NodeType, (BinaryExpression)binary.Left, (BinaryExpression)binary.Right);
} else
{
throw new ArgumentException($"Failed to evaluate expression of node type '{binary.NodeType.ToString()}'.");
}
}
private FilterDefinition<BsonDocument> BranchFilterDefinition(ExpressionType node, BinaryExpression binaryleft, BinaryExpression binaryright)
{
if (IsRelationalNode(binaryleft.NodeType) && IsRelationalNode(binaryright.NodeType))
{
ValidateParts(binaryleft);
ValidateParts(binaryright);
switch (node)
{
case ExpressionType.AndAlso:
return BuildFilterDefinition(binaryleft.NodeType, (MemberExpression)binaryleft.Left, (ConstantExpression)binaryleft.Right) &
BuildFilterDefinition(binaryright.NodeType, (MemberExpression)binaryright.Left, (ConstantExpression)binaryright.Right);
case ExpressionType.OrElse:
return BuildFilterDefinition(binaryleft.NodeType, (MemberExpression)binaryleft.Left, (ConstantExpression)binaryleft.Right) |
BuildFilterDefinition(binaryright.NodeType, (MemberExpression)binaryright.Left, (ConstantExpression)binaryright.Right);
default:
throw new ArgumentException($"'{node.ToString()}' operation not supported in expression.");
}
} else if (IsLogicalNode(binaryleft.NodeType) && IsRelationalNode(binaryright.NodeType))
{
ValidateOperands(binaryleft);
ValidateParts(binaryright);
switch (node)
{
case ExpressionType.AndAlso:
return BranchFilterDefinition(binaryleft.NodeType, (BinaryExpression)binaryleft.Left, (BinaryExpression)binaryleft.Right) &
BuildFilterDefinition(binaryright.NodeType, (MemberExpression)binaryright.Left, (ConstantExpression)binaryright.Right);
case ExpressionType.OrElse:
return BranchFilterDefinition(binaryleft.NodeType, (BinaryExpression)binaryleft.Left, (BinaryExpression)binaryleft.Right) |
BuildFilterDefinition(binaryright.NodeType, (MemberExpression)binaryright.Left, (ConstantExpression)binaryright.Right);
default:
throw new ArgumentException($"'{node.ToString()}' operation not supported in expression.");
}
} else if (IsRelationalNode(binaryleft.NodeType) && IsLogicalNode(binaryright.NodeType))
{
ValidateParts(binaryleft);
ValidateOperands(binaryright);
switch (node)
{
case ExpressionType.AndAlso:
return BuildFilterDefinition(binaryleft.NodeType, (MemberExpression)binaryleft.Left, (ConstantExpression)binaryleft.Right) &
BranchFilterDefinition(binaryright.NodeType, (BinaryExpression)binaryright.Left, (BinaryExpression)binaryright.Right);
case ExpressionType.OrElse:
return BuildFilterDefinition(binaryleft.NodeType, (MemberExpression)binaryleft.Left, (ConstantExpression)binaryleft.Right) |
BranchFilterDefinition(binaryright.NodeType, (BinaryExpression)binaryright.Left, (BinaryExpression)binaryright.Right);
default:
throw new ArgumentException($"'{node.ToString()}' operation not supported in expression.");
}
} else if (IsLogicalNode(binaryleft.NodeType) && IsLogicalNode(binaryright.NodeType))
{
ValidateOperands(binaryleft);
ValidateOperands(binaryright);
switch (node)
{
case ExpressionType.AndAlso:
return BranchFilterDefinition(binaryleft.NodeType, (BinaryExpression)binaryleft.Left, (BinaryExpression)binaryleft.Right) &
BranchFilterDefinition(binaryright.NodeType, (BinaryExpression)binaryright.Left, (BinaryExpression)binaryright.Right);
case ExpressionType.OrElse:
return BranchFilterDefinition(binaryleft.NodeType, (BinaryExpression)binaryleft.Left, (BinaryExpression)binaryleft.Right) |
BranchFilterDefinition(binaryright.NodeType, (BinaryExpression)binaryright.Left, (BinaryExpression)binaryright.Right);
default:
throw new ArgumentException($"'{node.ToString()}' operation not supported in expression.");
}
} else
{
throw new ArgumentException($"Failed to evaluate expression of node type '{node.ToString()}'.");
}
}
private FilterDefinition<BsonDocument> BuildFilterDefinition(ExpressionType node, MemberExpression left, ConstantExpression right)
{
switch (node)
{
case ExpressionType.Equal:
return Builders<BsonDocument>.Filter.Eq(left.Member.Name, right.Value);
case ExpressionType.GreaterThan:
return Builders<BsonDocument>.Filter.Gt(left.Member.Name, right.Value);
case ExpressionType.GreaterThanOrEqual:
return Builders<BsonDocument>.Filter.Gte(left.Member.Name, right.Value);
case ExpressionType.LessThan:
return Builders<BsonDocument>.Filter.Lt(left.Member.Name, right.Value);
case ExpressionType.LessThanOrEqual:
return Builders<BsonDocument>.Filter.Lte(left.Member.Name, right.Value);
case ExpressionType.NotEqual:
return Builders<BsonDocument>.Filter.Ne(left.Member.Name, right.Value);
default:
throw new ArgumentException($"'{node.ToString()}' comparison not supported in expression.");
}
}
private FilterDefinition<BsonDocument> BuildFilterDefinition(ExpressionType node, MemberExpression left, Expression right)
{
// complie the expression and assign to delegate
LambdaExpression lambda = Expression.Lambda(right);
Delegate d = lambda.Compile();
// invoke the delegate object to get the value
object value = d.DynamicInvoke(new object[0]);
// use the "_id" instead of the C# name
string name = left.Member.Name.Contains("Id") ? "_id" : left.Member.Name;
switch (node)
{
case ExpressionType.Equal:
return Builders<BsonDocument>.Filter.Eq(name, value);
case ExpressionType.GreaterThan:
return Builders<BsonDocument>.Filter.Gt(name, value);
case ExpressionType.GreaterThanOrEqual:
return Builders<BsonDocument>.Filter.Gte(name, value);
case ExpressionType.LessThan:
return Builders<BsonDocument>.Filter.Lt(name, value);
case ExpressionType.LessThanOrEqual:
return Builders<BsonDocument>.Filter.Lte(name, value);
case ExpressionType.NotEqual:
return Builders<BsonDocument>.Filter.Ne(name, value);
default:
throw new ArgumentException($"'{node.ToString()}' comparison not supported in expression.");
}
}
//
/// <summary>
/// Check if node type (NodeType) is Logical Operator
/// Currently supports:
/// AndAlso, OrElse
/// </summary>
/// <param name="node">Expression Type</param>
/// <returns>Boolean (True/False)</returns>
private bool IsLogicalNode(ExpressionType node)
{
// Inculde logical expression here..
return (node == ExpressionType.AndAlso || node == ExpressionType.OrElse) ? true : false;
}
/// <summary>
/// Check if node type (NodeType) is Relational Operator.
/// Currently supports:
/// Equal, Greater Than, Greater Than Equal, Less Than, Less Than Equal, Not Equal
/// </summary>
/// <param name="node">Expression Type</param>
/// <returns>Boolean (True/False)</returns>
private bool IsRelationalNode(ExpressionType node)
{
// Include relational expression here..
return (node == ExpressionType.Equal || node == ExpressionType.GreaterThan || node == ExpressionType.GreaterThanOrEqual ||
node == ExpressionType.LessThan || node == ExpressionType.LessThanOrEqual || node == ExpressionType.NotEqual) ? true : false;
}
private bool IsBinaryExpression(Expression<Func<T, bool>> expression)
{
if (expression.Body is BinaryExpression)
{
return true;
} else
{
throw new ArgumentException($"Binary expression expected in '{expression.ToString()}'.");
}
}
private void ValidateParts(BinaryExpression binary)
{
if (!(binary.Left is MemberExpression))
throw new ArgumentException($"Member expected in expression '{binary.ToString()}'.");
if (!(binary.Right is ConstantExpression) && binary.Right.Type.Name != "ObjectId")
throw new ArgumentException($"Constant or ObjectId expected in expression '{binary.ToString()}'.");
}
private void ValidateOperands(BinaryExpression binary)
{
if (!(binary.Left is BinaryExpression))
throw new ArgumentException($"Expression expected on left operand in '{binary.ToString()}'.");
if (!(binary.Right is BinaryExpression))
throw new ArgumentException($"Expression expected on right operand in '{binary.ToString()}'.");
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (MongoCollection != null)
{
MongoCollection = null;
}
}
}
/// <summary>
///
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}