DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/LastDataService.cs

65 lines
1.8 KiB
C#
Raw Normal View History

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<Tdto, TModel> : ILastDataService<Tdto> where Tdto : new()
{
private readonly IAsbCloudDbContext db;
public LastDataService(IAsbCloudDbContext db)
{
this.db = db;
}
public async Task<Tdto> 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<Tdto>(entity.Data.ToString());
return dto;
}
public async Task UpsertAsync(int idWell, int idCategory,
Tdto value, CancellationToken token = default)
{
var model = value.Adapt<TModel>();
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);
}
db.SaveChanges();
}
}
}