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 GetQueryReadOnly() => db.Set(); public async Task> GetHistoryAsync(IEnumerable 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()); return dtos; } public async Task>> GetLogAsync(IEnumerable 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>( e.Key, e.Select(s => s.Adapt()) )).ToDictionary(); return dtos; } public async Task SaveAsync(Guid setpointKey, object newValue, CancellationToken token) { try { var entity = new Setpoint() { Key = setpointKey, Value = newValue, IdUser = 0, // ToDo: откуда тянуть? Created = DateTimeOffset.Now.ToUniversalTime() }; await db.Set().AddAsync(entity, token); var result = await db.SaveChangesAsync(token); return result; } catch (Exception) { return 0; } } } }