69 lines
2.2 KiB
C#
69 lines
2.2 KiB
C#
using System.Linq.Expressions;
|
|
using MongoDB.Driver;
|
|
using ExpenseTracker.Application.Common.Interfaces.Repositories;
|
|
using ExpenseTracker.Domain.Entities;
|
|
|
|
namespace ExpenseTracker.Persistence.MongoDb.Repositories;
|
|
|
|
public abstract class BaseMongoDbRepository<TEntity, TKey> : IBaseRepository<TEntity, TKey>
|
|
where TKey : IEquatable<TKey>
|
|
where TEntity : EntityBase<TKey>
|
|
{
|
|
protected readonly MongoDbContext _dbContext;
|
|
protected IMongoCollection<TEntity> _collection;
|
|
|
|
public BaseMongoDbRepository(MongoDbContext dbContext, string collectionName)
|
|
{
|
|
_dbContext = dbContext;
|
|
_collection = _dbContext.GetCollection<TEntity>(collectionName);
|
|
}
|
|
|
|
public IQueryable<TEntity> Queryable => _collection.AsQueryable();
|
|
|
|
public async Task<TEntity> AddOneAsync(TEntity entity, CancellationToken cancellationToken)
|
|
{
|
|
_dbContext.AddCommand(() =>
|
|
_collection.InsertOneAsync(entity, null, cancellationToken)
|
|
);
|
|
|
|
return entity;
|
|
}
|
|
|
|
public async Task<IEnumerable<TEntity>> AddManyAsync(IEnumerable<TEntity> entities, CancellationToken cancellationToken)
|
|
{
|
|
_dbContext.AddCommand(
|
|
() => _collection.InsertManyAsync(entities, null, cancellationToken)
|
|
);
|
|
|
|
return entities;
|
|
}
|
|
|
|
|
|
public async Task<TEntity> UpdateOneAsync(TEntity entity, CancellationToken cancellationToken)
|
|
{
|
|
_dbContext.AddCommand(() =>
|
|
_collection.ReplaceOneAsync(
|
|
_dbContext.Session,
|
|
e => e.Id.Equals(entity.Id),
|
|
entity, new ReplaceOptions(),
|
|
cancellationToken)
|
|
);
|
|
|
|
return entity;
|
|
}
|
|
|
|
public async Task DeleteOneAsync(TKey id, CancellationToken cancellationToken)
|
|
{
|
|
_dbContext.AddCommand(() =>
|
|
_collection.DeleteOneAsync(_dbContext.Session, e => e.Id.Equals(id), null, cancellationToken)
|
|
);
|
|
}
|
|
|
|
public async Task DeleteManyAsync(Expression<Func<TEntity, bool>> predicate, CancellationToken cancellationToken)
|
|
{
|
|
_dbContext.AddCommand(() =>
|
|
_collection.DeleteManyAsync(_dbContext.Session, predicate, null, cancellationToken)
|
|
);
|
|
}
|
|
}
|