using Marten; namespace Brizco.Infrastructure.Marten; public class MartenRepository(IDocumentStore documentStore) : IMartenRepository where TMartenEntity : IMartenEntity { public async Task> GetEntitiesAsync(CancellationToken cancellation) { await using var session = documentStore.QuerySession(); var entities = await session.Query().ToListAsync(cancellation); return entities.ToList(); } public async Task> GetEntitiesAsync(Expression> expression, CancellationToken cancellation) { await using var session = documentStore.QuerySession(); var entities = await session.Query().Where(expression).ToListAsync(cancellation); return entities.ToList(); } public async Task> GetQueryAsync(Expression> expression) { await using var session = documentStore.QuerySession(); var entities = session.Query().Where(expression); return entities; } public async Task GetEntityAsync(Guid id, CancellationToken cancellation) { await using var session = documentStore.QuerySession(); var setting = await session.LoadAsync(id, cancellation); if (setting == null) throw new AppException($"{nameof(TMartenEntity)} not found", ApiResultStatusCode.NotFound); return setting; } public async Task GetEntityAsync(Expression> expression, CancellationToken cancellation) { await using var session = documentStore.QuerySession(); var entity = await session.Query().FirstOrDefaultAsync(expression, cancellation); return entity; } public async Task AddOrUpdateEntityAsync(TMartenEntity entity, CancellationToken cancellation) { if (entity == null) throw new AppException($"{nameof(entity)} is null", ApiResultStatusCode.BadRequest); await using var session = documentStore.LightweightSession(); session.Store(entity); await session.SaveChangesAsync(cancellation); } public async Task RemoveEntityAsync(TMartenEntity entity, CancellationToken cancellation) { if (entity == null) throw new AppException($"{nameof(entity)} is null", ApiResultStatusCode.BadRequest); await using var session = documentStore.LightweightSession(); session.Delete(entity); await session.SaveChangesAsync(cancellation); } }