persistence/Persistence.Repository/Repositories/SetpointRepository.cs
2024-11-18 15:05:12 +05:00

81 lines
2.1 KiB
C#

using Mapster;
using Microsoft.EntityFrameworkCore;
using Persistence.Database.Model;
using Persistence.Models;
using Persistence.Repositories;
namespace Persistence.Repository.Repositories
{
public class SetpointRepository : ISetpointRepository
{
private DbContext db;
public SetpointRepository(DbContext db)
{
this.db = db;
}
protected virtual IQueryable<Setpoint> GetQueryReadOnly() => db.Set<Setpoint>();
public async Task<IEnumerable<SetpointValueDto>> GetCurrent(IEnumerable<Guid> setpointKeys, CancellationToken token)
{
var query = GetQueryReadOnly();
var entities = await query
.Where(e => setpointKeys.Contains(e.Key))
.ToArrayAsync(token);
var dtos = entities.Select(e => e.Adapt<SetpointValueDto>());
return dtos;
}
public async Task<IEnumerable<SetpointValueDto>> GetHistory(IEnumerable<Guid> setpointKeys, DateTimeOffset historyMoment, CancellationToken token)
{
var query = GetQueryReadOnly();
var entities = await query
.Where(e => setpointKeys.Contains(e.Key) && e.Created.Date == historyMoment.Date)
.ToArrayAsync(token);
var dtos = entities.Select(e => e.Adapt<SetpointValueDto>());
return dtos;
}
public async Task<Dictionary<Guid, IEnumerable<SetpointLogDto>>> GetLog(IEnumerable<Guid> setpointKeys, CancellationToken token)
{
var query = GetQueryReadOnly();
var entities = await query
.Where(e => setpointKeys.Contains(e.Key))
.ToArrayAsync(token);
var dtos = entities
.GroupBy(e => e.Key)
.Select(e => new KeyValuePair<Guid, IEnumerable<SetpointLogDto>>(
e.Key,
e.Select(s => s.Adapt<SetpointLogDto>())
)).ToDictionary();
return dtos;
}
public async Task<int> Save(Guid setpointKey, object newValue, int idUser, CancellationToken token)
{
try
{
var entity = new Setpoint()
{
Key = setpointKey,
Value = newValue,
IdUser = idUser,
Created = DateTimeOffset.Now.ToUniversalTime()
};
await db.Set<Setpoint>().AddAsync(entity, token);
var result = await db.SaveChangesAsync(token);
return result;
}
catch (Exception)
{
return 0;
}
}
}
}