111 lines
2.7 KiB
C#
111 lines
2.7 KiB
C#
using System.Linq.Expressions;
|
|
using Microsoft.Extensions.Logging;
|
|
using NHibernate;
|
|
using NHibernate.Linq;
|
|
|
|
namespace Tiger.Storage;
|
|
|
|
public class Repository<T> : IRepository<T> where T : class
|
|
{
|
|
private readonly ISession _session;
|
|
private readonly ILogger<IRepository<T>> _logger;
|
|
|
|
public Repository(ISession session, ILogger<IRepository<T>> logger)
|
|
{
|
|
_session = session;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task<T?> FindAsync(object id)
|
|
{
|
|
try
|
|
{
|
|
return await _session.GetAsync<T>(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<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<IEnumerable<T>> FindByAsync(Expression<Func<T, bool>>? expression)
|
|
{
|
|
try
|
|
{
|
|
var query = _session.Query<T>();
|
|
|
|
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<T>();
|
|
}
|
|
}
|
|
|
|
public async Task<T?> FindOneByAsync(Expression<Func<T, bool>> expression)
|
|
{
|
|
try
|
|
{
|
|
return await _session.Query<T>().FirstOrDefaultAsync(expression);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Tried find single {Type} by query", typeof(T).Name);
|
|
return null;
|
|
}
|
|
}
|
|
} |