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 where T:class { private static IMongoCollection 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 mongoCollection_T = dataBase_T.GetCollection(collectonName_T.CollectionName); return mongoCollection_T; } public static async Task InsertManyAsync(IEnumerable documents, CancellationToken cancellationToken = default(CancellationToken)) { await GetMongoCollection().InsertManyAsync(documents, new InsertManyOptions() { IsOrdered = false }); } public static async Task DeleteManyAsync(Expression> 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> filter) { await GetMongoCollection().Find(filter).ToListAsync(); } public static void CreatIndexAsync(CreateIndexModel createIndexModel) { GetMongoCollection().Indexes.CreateOne(createIndexModel); } } }