Spaces:
Sleeping
Sleeping
SaluAi / src /Infrastructure /TelegramSaaS.Infrastructure /Persistence /Repositories /MongoRepository.cs
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq.Expressions; | |
| using System.Threading.Tasks; | |
| using MongoDB.Driver; | |
| using TelegramSaaS.Application.Common.Interfaces.Persistence; | |
| using TelegramSaaS.Domain.Common; | |
| namespace TelegramSaaS.Infrastructure.Persistence.Repositories; | |
| public class MongoRepository<T> : IRepository<T> where T : BaseEntity | |
| { | |
| protected readonly IMongoCollection<T> Collection; | |
| public MongoRepository(MongoDbContext context, string collectionName) | |
| { | |
| Collection = context.GetCollection<T>(collectionName); | |
| } | |
| public async Task<T?> GetByIdAsync(string id) | |
| { | |
| return await Collection.Find(x => x.Id == id).FirstOrDefaultAsync(); | |
| } | |
| public async Task<IEnumerable<T>> GetAllAsync() | |
| { | |
| return await Collection.Find(_ => true).ToListAsync(); | |
| } | |
| public async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate) | |
| { | |
| return await Collection.Find(predicate).ToListAsync(); | |
| } | |
| public async Task AddAsync(T entity) | |
| { | |
| entity.CreatedAt = DateTime.UtcNow; | |
| await Collection.InsertOneAsync(entity); | |
| } | |
| public async Task UpdateAsync(T entity) | |
| { | |
| entity.UpdatedAt = DateTime.UtcNow; | |
| await Collection.ReplaceOneAsync(x => x.Id == entity.Id, entity); | |
| } | |
| public async Task DeleteAsync(string id) | |
| { | |
| await Collection.DeleteOneAsync(x => x.Id == id); | |
| } | |
| } | |