MongoHelper.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using Business.Core.Attributes;
  2. using Business.Core.Configuration;
  3. using Business.Core.Web;
  4. using MongoDB.Driver;
  5. using System.Linq.Expressions;
  6. namespace Business.Core.Utilities
  7. {
  8. public class MongoHelper<T> where T:class
  9. {
  10. private static IMongoCollection<T> GetMongoCollection()
  11. {
  12. var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
  13. string mongodbUrl = configuration["ConnectionStrings:MongoDB"];
  14. MongoClient client = new MongoClient(mongodbUrl);
  15. CollectionNameAttribute? collectonName_T = typeof(T).GetCustomAttributes(typeof(CollectionNameAttribute), true).FirstOrDefault() as CollectionNameAttribute;
  16. IMongoDatabase dataBase_T = client.GetDatabase(collectonName_T?.DatabaseName);
  17. IMongoCollection<T> mongoCollection_T = dataBase_T.GetCollection<T>(collectonName_T?.CollectionName);
  18. return mongoCollection_T;
  19. }
  20. public static async Task InsertManyAsync(IEnumerable<T> documents, CancellationToken cancellationToken = default(CancellationToken))
  21. {
  22. await GetMongoCollection().InsertManyAsync(documents, new InsertManyOptions() { IsOrdered = false });
  23. }
  24. public static async Task DeleteManyAsync(Expression<Func<T, bool>> expression)
  25. {
  26. await GetMongoCollection().DeleteManyAsync(expression);
  27. }
  28. public static async Task InsertAsync(T documents, CancellationToken cancellationToken = default(CancellationToken))
  29. {
  30. await GetMongoCollection().InsertOneAsync(documents);
  31. }
  32. public static async Task FindAsync(Expression<Func<T, bool>> filter)
  33. {
  34. await GetMongoCollection().Find(filter).ToListAsync();
  35. }
  36. public static void CreatIndexAsync(CreateIndexModel<T> createIndexModel)
  37. {
  38. GetMongoCollection().Indexes.CreateOne(createIndexModel);
  39. }
  40. }
  41. }