using System.Linq.Expressions; using BuildingBlocks.Core.Model; using MongoDB.Driver; using MongoDB.Driver.Linq; namespace BuildingBlocks.Mongo; public class MongoRepository : IMongoRepository where TEntity : class, IAggregate { private readonly IMongoDbContext _context; protected readonly IMongoCollection DbSet; public MongoRepository(IMongoDbContext context) { _context = context; DbSet = _context.GetCollection(); } public void Dispose() { _context?.Dispose(); } public Task FindByIdAsync(TId id, CancellationToken cancellationToken = default) { return FindOneAsync(e => e.Id.Equals(id), cancellationToken); } public Task FindOneAsync( Expression> predicate, CancellationToken cancellationToken = default) { return DbSet.Find(predicate).SingleOrDefaultAsync(cancellationToken: cancellationToken)!; } public async Task> FindAsync( Expression> predicate, CancellationToken cancellationToken = default) { return await DbSet.Find(predicate).ToListAsync(cancellationToken: cancellationToken)!; } public async Task> GetAllAsync(CancellationToken cancellationToken = default) { return await DbSet.AsQueryable().ToListAsync(cancellationToken); } public Task> RawQuery( string query, CancellationToken cancellationToken = default, params object[] queryParams) { throw new NotImplementedException(); } public async Task AddAsync(TEntity entity, CancellationToken cancellationToken = default) { await DbSet.InsertOneAsync(entity, new InsertOneOptions(), cancellationToken); return entity; } public async Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default) { await DbSet.ReplaceOneAsync(e => e.Id.Equals(entity.Id), entity, new ReplaceOptions(), cancellationToken); return entity; } public Task DeleteRangeAsync(IReadOnlyList entities, CancellationToken cancellationToken = default) { return DbSet.DeleteOneAsync(e => entities.Any(i => e.Id.Equals(i.Id)), cancellationToken); } public Task DeleteAsync( Expression> predicate, CancellationToken cancellationToken = default) => DbSet.DeleteOneAsync(predicate, cancellationToken); public Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default) { return DbSet.DeleteOneAsync(e => e.Id.Equals(entity.Id), cancellationToken); } public Task DeleteByIdAsync(TId id, CancellationToken cancellationToken = default) { return DbSet.DeleteOneAsync(e => e.Id.Equals(id), cancellationToken); } }