89 lines
2.6 KiB
C#
89 lines
2.6 KiB
C#
using Mapster;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Persistence.Database.Model;
|
|
using Persistence.Models;
|
|
using Persistence.Repositories;
|
|
|
|
namespace Persistence.Repository.Repositories;
|
|
public class TimeSeriesDataRepository<TEntity, TDto> : ITimeSeriesDataRepository<TDto>
|
|
where TEntity : class, ITimestampedData, new()
|
|
where TDto : class, ITimeSeriesAbstractDto, new()
|
|
{
|
|
private DbContext db;
|
|
|
|
public TimeSeriesDataRepository(DbContext db)
|
|
{
|
|
this.db = db;
|
|
}
|
|
|
|
protected virtual IQueryable<TEntity> GetQueryReadOnly() => this.db.Set<TEntity>();
|
|
|
|
public virtual async Task<IEnumerable<TDto>> GetAsync(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
|
|
{
|
|
var query = GetQueryReadOnly();
|
|
var entities = await query.ToArrayAsync(token);
|
|
var dtos = entities.Select(e => e.Adapt<TDto>());
|
|
|
|
return dtos;
|
|
}
|
|
|
|
public virtual async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
|
|
{
|
|
var query = GetQueryReadOnly();
|
|
var minDate = await query.MinAsync(o => o.Date, token);
|
|
var maxDate = await query.MaxAsync(o => o.Date, token);
|
|
|
|
return new DatesRangeDto
|
|
{
|
|
From = minDate,
|
|
To = maxDate
|
|
};
|
|
}
|
|
|
|
public virtual async Task<IEnumerable<TDto>> GetGtDate(DateTimeOffset date, CancellationToken token)
|
|
{
|
|
var query = this.db.Set<TEntity>().Where(e => e.Date > date);
|
|
var entities = await query.ToArrayAsync(token);
|
|
|
|
var dtos = entities.Select(e => e.Adapt<TDto>());
|
|
|
|
return dtos;
|
|
}
|
|
|
|
public virtual async Task<int> InsertRange(IEnumerable<TDto> dtos, CancellationToken token)
|
|
{
|
|
var entities = dtos.Select(d => d.Adapt<TEntity>());
|
|
|
|
await db.Set<TEntity>().AddRangeAsync(entities, token);
|
|
var result = await db.SaveChangesAsync(token);
|
|
|
|
return result;
|
|
}
|
|
|
|
public async Task<IEnumerable<TDto>> GetLastAsync(int takeCount, CancellationToken token)
|
|
{
|
|
var query = GetQueryReadOnly()
|
|
.OrderByDescending(e => e.Date)
|
|
.Take(takeCount);
|
|
|
|
var entities = await query.ToArrayAsync(token);
|
|
var dtos = entities.Select(e => e.Adapt<TDto>());
|
|
|
|
return dtos;
|
|
}
|
|
|
|
public async Task<TDto?> GetFirstAsync(CancellationToken token)
|
|
{
|
|
var query = GetQueryReadOnly()
|
|
.OrderBy(e => e.Date);
|
|
|
|
var entity = await query.FirstOrDefaultAsync(token);
|
|
|
|
if(entity == null)
|
|
return null;
|
|
|
|
var dto = entity.Adapt<TDto>();
|
|
return dto;
|
|
}
|
|
}
|