TigerEmu/Storage/Repository.cs

111 lines
2.7 KiB
C#
Raw Permalink Normal View History

2023-09-23 12:20:45 +00:00
using System.Linq.Expressions;
using Microsoft.Extensions.Logging;
2023-09-23 12:20:45 +00:00
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;
2023-09-23 12:20:45 +00:00
public Repository(ISession session, ILogger<IRepository<T>> logger)
2023-09-23 12:20:45 +00:00
{
_session = session;
_logger = logger;
2023-09-23 12:20:45 +00:00
}
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;
}
2023-09-23 12:20:45 +00:00
}
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);
}
2023-09-23 12:20:45 +00:00
}
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);
}
}
2023-09-23 12:20:45 +00:00
public async Task<IEnumerable<T>> FindByAsync(Expression<Func<T, bool>>? expression)
{
try
{
var query = _session.Query<T>();
if (expression != null)
{
query = query.Where(expression);
}
2023-09-23 12:20:45 +00:00
return await query.ToListAsync();
}
catch (Exception ex)
2023-09-23 12:20:45 +00:00
{
_logger.LogError(ex, "Tried find many {Type} by query", typeof(T).Name);
return Array.Empty<T>();
2023-09-23 12:20:45 +00:00
}
}
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;
}
2023-09-23 12:20:45 +00:00
}
}