using AsbCloudApp.Services; using AsbCloudDb.Model; using Mapster; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace AsbCloudInfrastructure.Services { public class LastDataService : ILastDataService where Tdto : new() { private readonly IAsbCloudDbContext db; public LastDataService(IAsbCloudDbContext db) { this.db = db; } public async Task GetAsync(int idWell, int idCategory, CancellationToken token = default) { var entity = await db.LastData.AsNoTracking().FirstOrDefaultAsync(e => e.IdWell == idWell && e.IdCategory == idCategory, token) .ConfigureAwait(false); if (entity is null) return new Tdto(); var dto = JsonSerializer.Deserialize(entity.Data.ToString()); return dto; } public async Task UpsertAsync(int idWell, int idCategory, Tdto value, CancellationToken token = default) { var model = value.Adapt(); var entity = await db.LastData.AsNoTracking() .FirstOrDefaultAsync(ld => ld.IdWell == idWell && ld.IdCategory == idCategory, token) .ConfigureAwait(false); if (entity is not null) { entity.Data = model; db.LastData.Update(entity); } else { var newLastData = new LastData { IdWell = idWell, IdCategory = idCategory, Data = model }; db.LastData.Add(newLastData); } return await db.SaveChangesAsync(token); } } }