using MongoDB.Driver; using System.Linq.Expressions; using Modules.Library.Database.Database; using Modules.Library.Domain.Entities; namespace Modules.Library.Database.Repositories; public abstract class RepositoryBase(MongoDbContext context) : IRepository where T : Entity { protected abstract IMongoCollection GetCollections(MongoDbContext context); protected bool _useSoftDelete = true; public async Task AddAsync(T entity) { await GetCollections(context).InsertOneAsync(entity); return entity.Id; } public async Task DeleteAsync(T entity) { if (!_useSoftDelete) { var document = await GetCollections(context).FindOneAndDeleteAsync(q => q.Id == entity.Id); return document != null; } else return await SoftDeleteAsync(entity); } protected virtual Task SoftDeleteAsync(T entity) => throw new NotImplementedException(); public async Task> GetAllAsync() => await GetCollections(context).Find("{}").ToListAsync(); public async Task GetByIdAsync(Guid id) => await GetCollections(context).Find(q => q.Id == id).SingleAsync(); public async Task GetByIdOrDefaultAsync(Guid id) => await GetCollections(context).Find(q => q.Id == id).SingleOrDefaultAsync(); public async Task GetFirstWhere(Expression> predicate) => await GetCollections(context).Find(predicate).SingleAsync(); public async Task GetFirstOrDefaultWhere(Expression> predicate) => await GetCollections(context).Find(predicate).SingleOrDefaultAsync(); public async Task> GetRangeByIdsAsync(List ids) => await GetCollections(context).Find(q => ids.Contains(q.Id)).ToListAsync(); public async Task> GetWhere(Expression> predicate) => await GetCollections(context).Find(predicate).ToListAsync(); public async Task AnyWhere(Expression> predicate) => await GetCollections(context).Find(predicate).AnyAsync(); public async Task UpdateAsync(T entity) { //var document = await _context.PaymentCollections.FindOneAndReplaceAsync(q => q.Id == entity.Id, entity, new () { ReturnDocument = ReturnDocument.After }); var document = await GetCollections(context).FindOneAndReplaceAsync(q => q.Id == entity.Id, entity); return document != null; } }