2021-08-09 15:41:42 +05:00
|
|
|
|
using AsbCloudApp.Services;
|
2021-08-02 11:39:39 +05:00
|
|
|
|
using AsbCloudDb.Model;
|
|
|
|
|
using Mapster;
|
2021-08-03 17:55:28 +05:00
|
|
|
|
using System.Text.Json;
|
2021-08-11 16:54:42 +05:00
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
2021-08-11 10:16:01 +05:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2021-08-02 11:39:39 +05:00
|
|
|
|
|
|
|
|
|
namespace AsbCloudInfrastructure.Services
|
|
|
|
|
{
|
2021-08-03 17:55:28 +05:00
|
|
|
|
public class LastDataService<Tdto, TModel> : ILastDataService<Tdto> where Tdto : new()
|
2021-08-02 11:39:39 +05:00
|
|
|
|
{
|
|
|
|
|
private readonly IAsbCloudDbContext db;
|
|
|
|
|
|
2021-08-02 12:23:18 +05:00
|
|
|
|
public LastDataService(IAsbCloudDbContext db)
|
2021-08-02 11:39:39 +05:00
|
|
|
|
{
|
|
|
|
|
this.db = db;
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-11 16:54:42 +05:00
|
|
|
|
public async Task<Tdto> GetAsync(int idWell, int idCategory,
|
|
|
|
|
CancellationToken token = default)
|
2021-08-02 11:39:39 +05:00
|
|
|
|
{
|
2021-08-11 16:54:42 +05:00
|
|
|
|
var entity = await db.LastData.AsNoTracking().FirstOrDefaultAsync(e =>
|
2021-08-11 17:26:02 +05:00
|
|
|
|
e.IdWell == idWell && e.IdCategory == idCategory, token)
|
|
|
|
|
.ConfigureAwait(false);
|
2021-08-02 11:39:39 +05:00
|
|
|
|
|
2021-08-02 12:23:18 +05:00
|
|
|
|
if (entity is null)
|
2021-08-03 17:55:28 +05:00
|
|
|
|
return new Tdto();
|
2021-08-02 12:23:18 +05:00
|
|
|
|
|
2021-08-03 17:55:28 +05:00
|
|
|
|
var dto = JsonSerializer.Deserialize<Tdto>(entity.Data.ToString());
|
2021-08-02 11:39:39 +05:00
|
|
|
|
return dto;
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-11 16:54:42 +05:00
|
|
|
|
public async Task UpsertAsync(int idWell, int idCategory,
|
|
|
|
|
Tdto value, CancellationToken token = default)
|
2021-08-02 11:39:39 +05:00
|
|
|
|
{
|
|
|
|
|
var model = value.Adapt<TModel>();
|
2021-08-02 12:23:18 +05:00
|
|
|
|
|
2021-08-11 16:54:42 +05:00
|
|
|
|
var entity = await db.LastData.AsNoTracking()
|
|
|
|
|
.FirstOrDefaultAsync(ld => ld.IdWell == idWell &&
|
2021-08-11 17:26:02 +05:00
|
|
|
|
ld.IdCategory == idCategory, token)
|
|
|
|
|
.ConfigureAwait(false);
|
2021-08-02 12:23:18 +05:00
|
|
|
|
|
|
|
|
|
if (entity is not null)
|
|
|
|
|
{
|
|
|
|
|
entity.Data = model;
|
|
|
|
|
db.LastData.Update(entity);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2021-08-09 15:41:42 +05:00
|
|
|
|
var newLastData = new LastData
|
|
|
|
|
{
|
2021-08-02 18:35:36 +05:00
|
|
|
|
IdWell = idWell,
|
|
|
|
|
IdCategory = idCategory,
|
2021-08-02 12:23:18 +05:00
|
|
|
|
Data = model
|
|
|
|
|
};
|
|
|
|
|
db.LastData.Add(newLastData);
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-02 18:35:36 +05:00
|
|
|
|
db.SaveChanges();
|
2021-08-02 11:39:39 +05:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|