using System.Linq.Expressions; using Microsoft.Extensions.Logging; using NHibernate; using NHibernate.Linq; namespace Tiger.Storage; public class Repository : IRepository where T : class { private readonly ISession _session; private readonly ILogger> _logger; public Repository(ISession session, ILogger> logger) { _session = session; _logger = logger; } public async Task FindAsync(object id) { try { return await _session.GetAsync(id); } catch (Exception ex) { _logger.LogError(ex, "Tried to get {Type} with id {Id}", typeof(T).Name, id); return null; } } public async Task SaveAsync(T entity) { try { await _session.SaveOrUpdateAsync(entity); await _session.FlushAsync(); } catch (Exception ex) { _logger.LogError(ex, "Tried to save {Type}", typeof(T).Name); } } public async Task SaveManyAsync(params T[] entities) { try { foreach (var entity in entities) { await _session.SaveOrUpdateAsync(entity); } await _session.FlushAsync(); } catch (Exception ex) { _logger.LogError(ex, "Tried to save many {Type}", typeof(T).Name); } } public async Task SaveManyAsync(IEnumerable entities) { try { foreach (var entity in entities) { await _session.SaveOrUpdateAsync(entity); } await _session.FlushAsync(); } catch (Exception ex) { _logger.LogError(ex, "Tried to save many {Type}", typeof(T).Name); } } public async Task> FindByAsync(Expression>? expression) { try { var query = _session.Query(); if (expression != null) { query = query.Where(expression); } return await query.ToListAsync(); } catch (Exception ex) { _logger.LogError(ex, "Tried find many {Type} by query", typeof(T).Name); return Array.Empty(); } } public async Task FindOneByAsync(Expression> expression) { try { return await _session.Query().FirstOrDefaultAsync(expression); } catch (Exception ex) { _logger.LogError(ex, "Tried find single {Type} by query", typeof(T).Name); return null; } } }