using MongoDB.Driver; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Reflection; using Tango.DAL.Attributes; using System.Linq.Expressions; using MongoDB.Driver.Linq; namespace Tango.DAL.Mongo { public class MongoRepository : IRepository where T : Entity { private IMongoDatabase _database; private MongoClient _client; private IMongoCollection _collection; public MongoRepository(MongoDataBaseSettings settings) { _client = new MongoClient(settings.Address); _database = _client.GetDatabase(settings.DatabaseName); } private IMongoCollection GetCollection() { if (_collection == null) { _collection = _database.GetCollection(typeof(T).GetCustomAttribute().Name); } return _collection; } public async Task> GetAllAsync() { return await (await GetCollection().FindAsync(x => true)).ToListAsync(); } public async Task> GetAsync(Expression> filter) { return await (await GetCollection().FindAsync(filter)).ToListAsync(); } public async Task ReplaceAsync(T entity) { await GetCollection().ReplaceOneAsync(x => x.ID == entity.ID, entity); return entity; } public async Task DeleteAsync(Expression> filter) { return (await GetCollection().DeleteOneAsync(filter)).DeletedCount; } public async Task Insert(T entity) { await GetCollection().InsertOneAsync(entity); return entity; } public Task Count() { return GetCollection().CountDocumentsAsync(x => true); } public Task Count(Expression> filter) { return GetCollection().CountDocumentsAsync(filter); } public void Dispose() { } } }