| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- using Business.Core.Attributes;
- using Business.Core.Configuration;
- using Business.Core.Web;
- using MongoDB.Driver;
- using System.Linq.Expressions;
- namespace Business.Core.Utilities
- {
- public class MongoHelper<T> where T:class
- {
- private static IMongoCollection<T> GetMongoCollection()
- {
- var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
- string mongodbUrl = configuration["ConnectionStrings:MongoDB"];
- MongoClient client = new MongoClient(mongodbUrl);
- CollectionNameAttribute? collectonName_T = typeof(T).GetCustomAttributes(typeof(CollectionNameAttribute), true).FirstOrDefault() as CollectionNameAttribute;
- IMongoDatabase dataBase_T = client.GetDatabase(collectonName_T?.DatabaseName);
- IMongoCollection<T> mongoCollection_T = dataBase_T.GetCollection<T>(collectonName_T?.CollectionName);
- return mongoCollection_T;
- }
- public static async Task InsertManyAsync(IEnumerable<T> documents, CancellationToken cancellationToken = default(CancellationToken))
- {
- await GetMongoCollection().InsertManyAsync(documents, new InsertManyOptions() { IsOrdered = true });
- }
- public static async Task DeleteManyAsync(Expression<Func<T, bool>> expression)
- {
- await GetMongoCollection().DeleteManyAsync(expression);
- }
- public static async Task InsertAsync(T documents, CancellationToken cancellationToken = default(CancellationToken))
- {
- await GetMongoCollection().InsertOneAsync(documents);
- }
- public static async Task FindAsync(Expression<Func<T, bool>> filter)
- {
- await GetMongoCollection().Find(filter).ToListAsync();
- }
- public static void CreatIndexAsync(CreateIndexModel<T> createIndexModel)
- {
- GetMongoCollection().Indexes.CreateOne(createIndexModel);
- }
- }
- }
|