MyBookmark/Modules.Library.Database/Repositories/RepositoryBase.cs
2024-09-04 23:08:56 +03:00

58 lines
2.4 KiB
C#

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<T>(MongoDbContext context) : IRepository<T> where T : Entity
{
protected abstract IMongoCollection<T> GetCollections(MongoDbContext context);
protected bool _useSoftDelete = true;
public async Task<Guid> AddAsync(T entity)
{
await GetCollections(context).InsertOneAsync(entity);
return entity.Id;
}
public async Task<bool> 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<bool> SoftDeleteAsync(T entity) => throw new NotImplementedException();
public async Task<List<T>> GetAllAsync() => await GetCollections(context).Find("{}").ToListAsync();
public async Task<T> GetByIdAsync(Guid id) => await GetCollections(context).Find(q => q.Id == id).SingleAsync();
public async Task<T?> GetByIdOrDefaultAsync(Guid id) => await GetCollections(context).Find(q => q.Id == id).SingleOrDefaultAsync();
public async Task<T> GetFirstWhere(Expression<Func<T, bool>> predicate) =>
await GetCollections(context).Find(predicate).SingleAsync();
public async Task<T?> GetFirstOrDefaultWhere(Expression<Func<T, bool>> predicate) =>
await GetCollections(context).Find(predicate).SingleOrDefaultAsync();
public async Task<List<T>> GetRangeByIdsAsync(List<Guid> ids) =>
await GetCollections(context).Find(q => ids.Contains(q.Id)).ToListAsync();
public async Task<List<T>> GetWhere(Expression<Func<T, bool>> predicate) =>
await GetCollections(context).Find(predicate).ToListAsync();
public async Task<bool> AnyWhere(Expression<Func<T, bool>> predicate) =>
await GetCollections(context).Find(predicate).AnyAsync();
public async Task<bool> 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;
}
}