forked from RickStrahl/WestwindToolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MongoDbBusinessBase.cs
1245 lines (1037 loc) · 40.3 KB
/
MongoDbBusinessBase.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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using Newtonsoft.Json;
using Westwind.Data.MongoDb.Properties;
using Westwind.Utilities;
namespace Westwind.Data.MongoDb
{
/// <summary>
/// Light weight MongoDb Business object base class
/// that acts as a logical business container for MongoDb
/// databases.
///
/// Subclasses of this business object should be used to implement most data
/// related logic that deals with creating, updating, removing and querying
/// of data use the MongoDb query or LINQ operators.
///
/// The business object provides base CRUD methods like Load, NewEntity,
/// Remove that act on the specified entity type. The Save() method uses
/// the EF specific context based SaveChanges
/// which saves all pending changes (not just those for the current entity
/// and its relations).
///
/// These business objects should be used as atomically as possible and
/// call Save() as often as possible to update pending data.
/// </summary>
/// <typeparam name="TEntity">
/// The type of the entity that this business object is tied to.
/// Note that you can access any of the context's entities - this entity
/// is meant as a 'top level' entity that controls the operations of
/// the CRUD methods. Maps to the Entity property on this class
/// </typeparam>
/// <typeparam name="TMongoContext">
/// A MongoDbContext type that configures MongoDb driver behavior and startup operation.
/// </typeparam>
public class MongoDbBusinessBase<TEntity, TMongoContext> : IDisposable, IBusinessObject
where TEntity : class, new()
where TMongoContext : MongoDbContext, new()
{
/// <summary>
/// Instance of the MongoDb core database instance.
/// Set internally when the driver is initialized.
/// </summary>
public MongoDatabase Database { get; set; }
protected string CollectionName { get; set; }
protected Type EntityType = typeof(TEntity);
protected TMongoContext Context = new TMongoContext();
/// <summary>
/// Re-usable MongoDb Collection instance.
/// Set internally when the driver is initialized
/// and accessible after that.
/// </summary>
public MongoCollection<TEntity> Collection
{
get
{
if (_collection == null)
_collection = Database.GetCollection<TEntity>(CollectionName);
return _collection;
}
}
private MongoCollection<TEntity> _collection;
/// <summary>
/// A collection that holds validation errors after Validate()
/// or Save with AutoValidate on is called
/// </summary>
public ValidationErrorCollection ValidationErrors
{
get
{
if (_validationErrors == null)
_validationErrors = new ValidationErrorCollection();
return _validationErrors;
}
}
private ValidationErrorCollection _validationErrors;
/// <summary>
/// Determines whether or not the Save operation causes automatic
/// validation. Default is false.
/// </summary>
public bool AutoValidate { get; set; }
/// <summary>
/// Internally loaded instance from load and newentity calls
/// </summary>
public TEntity Entity { get; set; }
/// <summary>
/// Error Message set by the last operation. Check if
/// results of a method call return an error status.
/// </summary>
public string ErrorMessage
{
get
{
if (ErrorException == null)
return "";
return ErrorException.Message;
}
set
{
if (string.IsNullOrEmpty(value))
ErrorException = null;
else
// Assign a new exception
ErrorException = new ApplicationException(value);
}
}
/// <summary>
/// Instance of an exception object that caused the last error
/// </summary>
public Exception ErrorException
{
get { return _errorException; }
set { _errorException = value; }
}
[NonSerialized]
private Exception _errorException;
#region ObjectInitializers
/// <summary>
/// Base constructor using default behavior loading context by
/// connectionstring name.
/// </summary>
/// <param name="connectionString">Connection string name</param>
public MongoDbBusinessBase(string collection = null, string database = null, string connectionString = null)
{
InitializeInternal();
Context = new TMongoContext();
Database = GetDatabase(collection, database, connectionString);
if (!Database.CollectionExists(CollectionName))
{
if (string.IsNullOrEmpty(CollectionName))
CollectionName = Pluralizer.Pluralize(EntityType.Name);
Database.CreateCollection(CollectionName);
}
Initialize();
}
/// <summary>
/// Specialized CreateContext that accepts a connection string and provider.
/// Creates a new context based on a Connection String name or
/// connection string.
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
/// <remarks>Important:
/// This only works if you implement a DbContext contstructor on your custom context
/// that accepts a connectionString parameter.
/// </remarks>
protected virtual MongoDatabase GetDatabase(string collection = null,
string database = null,
string serverString = null)
{
var db = Context.GetDatabase(serverString, database);
if (string.IsNullOrEmpty(collection))
collection = Pluralizer.Pluralize(typeof(TEntity).Name);
CollectionName = collection;
return db;
}
/// <summary>
/// Override to hook post Context intialization
/// Fired by all constructors.
/// </summary>
protected virtual void Initialize()
{
}
/// <summary>
/// Internal common pre-Context creation initialization code
/// fired by all constructors
/// </summary>
private void InitializeInternal()
{
// nothing to do yet, but we'll use this for sub objects
// and potential meta data pre-parsing
}
#endregion
/// <summary>
/// Finds an individual entity based on the entity tyep
/// of this application.
/// </summary>
/// <param name="query"></param>
/// <param name="collectionName"></param>
/// <returns></returns>
public TEntity FindOne(IMongoQuery query, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
return Database.GetCollection<TEntity>(collectionName).FindOne(query);
}
/// <summary>
/// Finds an individual entity based on the entity type passed in
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <param name="collectionName"></param>
/// <returns></returns>
public T FindOne<T>(IMongoQuery query, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
return Database.GetCollection<T>(collectionName).FindOne(query);
}
public IEnumerable<T> Find<T>(IMongoQuery query, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
return Database.GetCollection<T>(collectionName).Find(query);
}
/// <summary>
/// Allows you to query for a single entity using a Mongo Shell query
/// string. Uses the default entity defined.
/// </summary>
/// <param name="jsonQuery">Json object query string</param>
/// <param name="collectionName">Optional - name of the collection to search</param>
/// <returns>Collection of items or null if none</returns>
public TEntity FindOneFromString(string jsonQuery, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
var query = GetQueryFromString(jsonQuery);
return Database.GetCollection<TEntity>(collectionName).FindOne(query);
}
/// <summary>
/// Allows you to query for a single entity using a Mongo Shell query
/// string. Uses the entity type passed.
/// </summary>
/// <param name="jsonQuery">Json object query string</param>
/// <param name="collectionName">Optional - name of the collection to search</param>
/// <returns>Collection of items or null if none</returns>
public T FindOneFromString<T>(string jsonQuery, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
var query = GetQueryFromString(jsonQuery);
return Database.GetCollection<T>(collectionName).FindOne(query);
}
/// <summary>
/// Allows you to query for a single entity using a Mongo Shell query
/// string. Uses the entity type passed.
/// </summary>
/// <param name="jsonQuery">Json object query string</param>
/// <param name="collectionName">Optional - name of the collection to search</param>
/// <returns>Collection of items or null if none</returns>
public string FindOneFromStringJson(string jsonQuery, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
var query = GetQueryFromString(jsonQuery);
var cursor = Database.GetCollection(collectionName).FindOne(query);
if (cursor == null)
return null;
return cursor.ToJson();
}
public IEnumerable<TEntity> FindAll(string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
return Database.GetCollection<TEntity>(collectionName).FindAll();
}
public IEnumerable<T> FindAll<T>(string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
return Database.GetCollection<T>(collectionName).FindAll();
}
public IEnumerable<TEntity> FindFromString(string jsonQuery, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
var query = GetQueryFromString(jsonQuery);
var items = Database.GetCollection<TEntity>(collectionName).Find(query);
return items;
}
/// <summary>
/// Allows you to query Mongo using a Mongo Shell query
/// string and explicitly specify the result type.
/// </summary>
/// <param name="jsonQuery">Json object query string</param>
/// <param name="collectionName">Optional - name of the collection to search</param>
/// <returns>Collection of items or null if none</returns>
public IEnumerable<T> FindFromString<T>(string jsonQuery, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
var query = GetQueryFromString(jsonQuery);
var items = Database.GetCollection<T>(collectionName).Find(query);
return items;
}
/// <summary>
/// Allows you to query Mongo using a Mongo Shell query
/// string.
/// </summary>
/// <param name="jsonQuery">Json object query string</param>
/// <param name="collectionName">Optional - name of the collection to search</param>
/// <returns>Collection of items or null if none</returns>
public string FindFromStringJson(string jsonQuery, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
var query = GetQueryFromString(jsonQuery);
var cursor = Database.GetCollection(collectionName).Find(query);
return cursor.ToJson();
}
/// <summary>
/// Allows you to query Mongo using a Mongo Shell query
/// by providing a .NET object that is translated into
/// the appropriate JSON/BSON structure.
///
/// This might be easier to write by hand than JSON strings
/// in C# code.
/// </summary>
/// <param name="queryObject">Any .NET object that conforms to Mongo query object structure</param>
/// <param name="collectionName">Optional - name of the collection to search</param>
/// <returns>Collection of items or null if none</returns>
public IEnumerable<TEntity> FindFromObject(object queryObject, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
var query = new QueryDocument(queryObject.ToBsonDocument());
var items = Database.GetCollection<TEntity>(collectionName).Find(query);
return items;
}
/// <summary>
/// Allows you to query Mongo using a Mongo Shell query
/// by providing a .NET object that is translated into
/// the appropriate JSON/BSON structure. This version
/// allows you to specify the result type explicitly.
///
/// This might be easier to write by hand than JSON strings
/// in C# code.
/// </summary>
/// <param name="queryObject">Any .NET object that conforms to Mongo query object structure</param>
/// <param name="collectionName">Optional - name of the collection to search</param>
/// <returns>Collection of items or null if none</returns>
public IEnumerable<T> FindFromObject<T>(object queryObject, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
var query = new QueryDocument(queryObject.ToBsonDocument());
var items = Database.GetCollection<T>(collectionName).Find(query);
return items;
}
/// <summary>
/// Creates a Bson Query document from a Json String.
///
/// You can pass this as a Query operation to any of the
/// Collection methods that expect a query.
/// </summary>
/// <param name="jsonQuery"></param>
/// <returns></returns>
public QueryDocument GetQueryFromString(string jsonQuery)
{
return new QueryDocument(BsonSerializer.Deserialize<BsonDocument>(jsonQuery));
}
/// <summary>
/// Creates a new instance of an Entity tracked
/// by the DbContext.
/// </summary>
/// <returns></returns>
public virtual TEntity NewEntity()
{
Entity = new TEntity();
OnNewEntity(Entity);
if (Entity == null)
return null;
return Entity;
}
/// <summary>
/// Adds a new entity as if it was created and fires
/// the OnNewEntity internally. If NULL is passed in
/// a brand new entity is created and passed back.
///
/// This allows for external creation of the entity
/// and then adding the entity to the context after
/// the fact.
/// </summary>
/// <param name="entity">An entity instance</param>
/// <returns></returns>
public virtual TEntity NewEntity(TEntity entity)
{
if (entity == null)
return NewEntity();
Entity = entity;
OnNewEntity(Entity);
if (Entity == null)
return null;
return Entity;
}
/// <summary>
/// Overridable method that allows adding post NewEntity functionaly
/// </summary>
/// <param name="entity"></param>
protected virtual void OnNewEntity(TEntity entity)
{
}
/// <summary>
/// Loads in instance based on its string id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public TEntity Load(string id)
{
return LoadBase(id);
}
/// <summary>
/// Loads in instance based on its string id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public TEntity Load(int id)
{
return LoadBase(id);
}
/// <summary>
/// Loads an instance based on its key field id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
protected virtual TEntity LoadBase(string id)
{
if (string.IsNullOrEmpty(id))
return null;
Entity = Collection.FindOneByIdAs(typeof(TEntity), new BsonString(id)) as TEntity;
if (Entity == null)
{
SetError("No match found.");
return null;
}
OnEntityLoaded(Entity);
return Entity;
}
/// <summary>
/// Loads an instance based on its key field id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
protected virtual TEntity LoadBase(int id)
{
Entity = Collection.FindOneByIdAs(typeof(TEntity), id) as TEntity;
if (Entity == null)
{
SetError("No match found.");
return null;
}
OnEntityLoaded(Entity);
return Entity;
}
/// <summary>
/// Loads an entity based on a Lambda expression
/// </summary>
/// <param name="whereClauseLambda"></param>
/// <returns></returns>
protected virtual TEntity LoadBase(Expression<Func<TEntity, bool>> whereClauseLambda)
{
SetError();
Entity = null;
try
{
var query = Query<TEntity>.Where(whereClauseLambda);
Entity = Database.GetCollection<TEntity>(CollectionName).FindOne(query);
if (Entity != null)
OnEntityLoaded(Entity);
return Entity;
}
catch (InvalidOperationException)
{
// Handles errors where an invalid Id was passed, but SQL is valid
SetError(Resources.CouldntLoadEntityInvalidKeyProvided);
return null;
}
catch (Exception ex)
{
// handles Sql errors
SetError(ex);
}
return null;
}
/// <summary>
/// Fired after an entity has been loaded with the .Load() method
/// </summary>
/// <param name="entity"></param>
protected virtual void OnEntityLoaded(TEntity entity)
{
}
/// <summary>
/// removes an individual entity instance.
///
/// This method allows specifying an entity in a dbSet other
/// then the main one as long as it's specified by the dbSet
/// parameter.
/// </summary>
/// <param name="entity"></param>
/// <param name="dbSet">Optional -
/// Allows specifying the Collection to which the entity passed belongs.
/// If not specified the current Collection for the current entity is used </param>
/// <param name="saveChanges">Optional -
/// If true does a Context.SaveChanges. Set to false
/// when other changes in the Context are pending and you don't want them to commit
/// immediately
/// </param>
/// <param name="noTransaction">Optional -
/// If true the Delete operation is wrapped into a TransactionScope transaction that
/// ensures that OnBeforeDelete and OnAfterDelete all fire within the same Transaction scope.
/// Defaults to false as to improve performance.
/// </param>
public virtual bool Delete(TEntity entity)
{
if (entity == null)
entity = Entity;
if (entity == null)
return true;
if (!DeleteInternal(entity))
return false;
return true;
}
/// <summary>
/// Deletes an entity from the main entity set
/// based on a key value.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual bool Delete(string id)
{
var query = Query.EQ("_id", new BsonString(id));
var result = Collection.Remove(query);
if (result.HasLastErrorMessage)
{
SetError(result.ErrorMessage);
return false;
}
return true;
}
public virtual bool Delete(int id)
{
var query = Query.EQ("_id", id);
var result = Collection.Remove(query);
if (result.HasLastErrorMessage)
{
SetError(result.ErrorMessage);
return false;
}
return true;
}
/// <summary>
/// Actual delete operation that removes an entity
/// </summary>
private bool DeleteInternal(TEntity entity)
{
if (!OnBeforeDelete(entity))
return false;
try
{
var query = Query.EQ("_id", new BsonString(((dynamic)entity).Id.ToString()));
var result = Collection.Remove(query);
if (result.HasLastErrorMessage)
{
SetError(result.ErrorMessage);
return false;
}
if (!OnAfterDelete(entity))
return false;
}
catch (Exception ex)
{
SetError(ex, true);
return false;
}
return true;
}
/// <summary>
/// Called before a delete operation occurs
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
protected virtual bool OnBeforeDelete(TEntity entity)
{
return true;
}
/// <summary>
/// Called after a resource is deleted. Runs within the same
/// transaction scope
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
protected virtual bool OnAfterDelete(TEntity entity)
{
return true;
}
//protected DbTransaction BeginTransaction(IsolationLevel level = IsolationLevel.Unspecified)
//{
// if (Context.DatabaseName.Connection.State != ConnectionState.Open)
// Context.DatabaseName.Connection.Open();
// return Context.DatabaseName.Connection.BeginTransaction(level);
//}
//public void CommitTransaction()
//{
// Context.DatabaseName.Connection.
//}
//public void RollbackTransaction()
//{
//}
/// <summary>
/// Saves all changes.
/// </summary>
/// <remarks>
/// This method calls Context.SaveChanges() so it saves
/// all changes made in the context not just changes made
/// to the current entity. It's crucial to Save() as
/// atomically as possible or else use separate Business
/// object instances with separate contexts.
/// </remarks>
/// <returns></returns>
public bool Save(TEntity entity = null, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
if (entity == null)
entity = Entity;
// hook point - allow logic to abort saving
if (!OnBeforeSave(entity))
return false;
// now do validations
if (AutoValidate)
{
if (!Validate(entity))
return false;
}
try
{
var result = Collection.Save(entity);
if (result.HasLastErrorMessage)
{
SetError(result.LastErrorMessage);
return false;
}
}
catch (Exception ex)
{
SetError(ex, true);
return false;
}
if (!OnAfterSave(Entity))
return false;
return true;
}
/// <summary>
/// Saves an entity based on a provided type.
/// </summary>
/// <remarks>
/// This version of Save() does not run Validation, or
/// before and after save events since it's not tied to
/// the current entity type. If you want the full featured
/// save use the non-generic Save() operation.
/// </remarks>
/// <returns></returns>
public bool Save<T>(T entity, string collectionName = null)
where T : class, new()
{
if (string.IsNullOrEmpty(collectionName))
collectionName = Pluralizer.Pluralize(typeof(T).Name);
if (entity == null)
{
SetError("No entity to save passed.");
return false;
}
try
{
var result = Database.GetCollection(collectionName).Save(entity);
if (result.HasLastErrorMessage)
{
SetError(result.LastErrorMessage);
return false;
}
}
catch (Exception ex)
{
SetError(ex, true);
return false;
}
return true;
}
/// <summary>
/// Parses an .NET object into a BSON document
/// </summary>
/// <param name="data">.NET object ir value</param>
/// <returns></returns>
public BsonDocument ParseObject(object data)
{
string json = JsonConvert.SerializeObject(data);
BsonDocument doc = null;
try
{
doc = BsonDocument.Parse(json);
if (doc == null)
{
SetError("No entity to save passed.");
return null;
}
}
catch (Exception ex)
{
SetError(ex, true);
return null;
}
return doc;
}
/// <summary>
/// Saves a Json string based document into a collection.
/// </summary>
/// <remarks>
/// If you have _id or Id properties make sure those are strings or BSON Ids.
/// Integer values cannot be saved as Ids.
/// </remarks>
/// <param name="collectionName">Name of the collection to write to</param>
/// <returns>Id of object saved</returns>
public string SaveFromJson(string entityJson, string collectionName = null)
{
if (string.IsNullOrEmpty(collectionName))
collectionName = CollectionName;
if (string.IsNullOrEmpty(entityJson))
{
SetError("No entity to save passed.");
return null;
}
BsonDocument doc = null;
try
{
doc = BsonSerializer.Deserialize<BsonDocument>(entityJson); //BsonDocument.Parse(entityJson);
if (doc == null)
{
SetError("No entity to save passed.");
return null;
}
}
catch (Exception ex)
{
SetError(ex, true);
return null;
}
return SaveFromDocument(doc,collectionName);
}
/// <summary>
/// Saves a generic object to a collection
/// </summary>
/// <param name="data">.NET object to save</param>
/// <param name="collectionName">name of the collection to save to</param>
/// <returns></returns>
public string SaveFromObject(object data, string collectionName = null)
{
var doc = ParseObject(data);
if (doc == null)
return null;
return SaveFromDocument(doc, collectionName);
}
/// <summary>
/// Saves a BSON document to a collection by name
/// </summary>
/// <param name="doc">A populated BSON document</param>
/// <param name="collectionName">Collection to save to</param>
/// <returns></returns>
public string SaveFromDocument(BsonDocument doc, string collectionName = null)
{
if (doc == null)
{
SetError("No entity to save passed.");
return null;
}
try
{
var result = Database.GetCollection(collectionName).Save(doc);
if (result.HasLastErrorMessage)
{
SetError(result.LastErrorMessage);
return null;
}
var id = doc["_id"].AsString;
return id;
}
catch (Exception ex)
{
SetError(ex, true);
return null;
}
}
/// <summary>
/// Hook point fired just before the save method is called.
///
/// Override this method to fix up entity values before a save
/// operation occurs.
/// </summary>
/// <returns>return true to save or false to avoid saving</returns>
/// <param name="entity"></param>
protected virtual bool OnBeforeSave(TEntity entity)
{
return true;
}
/// <summary>
/// Hook point fired after the Save operation has completed
/// successfully. Note doesn't fire if the Save() operation
/// fails.
///
/// Override this method to fix up or fire actions after
/// the Save operation completes.
/// </summary>
/// <param name="entity"></param>
protected virtual bool OnAfterSave(TEntity entity)
{
return true;
}
/// <summary>
/// Validate() is used to validate business rules on the business object.
/// Validates both EF entity validation rules on pending changes as well
/// as any custom validation rules you implement in the OnValidate() method.
///
/// Do not override this method for custom Validation(). Instead override
/// OnValidate() or add error entries to the ValidationErrors collectionName.
/// <remarks>
/// If the AutoValidate flag is set to true causes Save()
/// to automatically call this method. Must be overridden to perform any
/// validation.
/// </remarks>
/// <seealso>Class wwBusiness Class ValidationErrorCollection</seealso>
/// </summary>
/// <param name="entity">Optional entity to validate. Defaults to this.Entity</param>
/// <param name="clearValidationErrors">If true clears all validation errors before processing rules</param>
/// <returns>True or False.</returns>
public bool Validate(TEntity entity = null, bool clearValidationErrors = false)
{
if (clearValidationErrors)
ValidationErrors.Clear();
if (entity == null)
entity = Entity;
// No entity - no validation errors
if (entity == null)
return true;