DD.WellWorkover.Cloud/AsbCloudInfrastructure/Repository/SetpointsRequestRepository.cs

79 lines
2.8 KiB
C#
Raw Permalink Normal View History

using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
using AsbCloudApp.Exceptions;
2024-08-19 10:01:07 +05:00
namespace AsbCloudInfrastructure.Repository;
2024-08-19 10:01:07 +05:00
public class SetpointsRequestRepository : CrudWellRelatedCacheRepositoryBase<SetpointsRequestDto, SetpointsRequest>
{
private readonly IWellService wellService;
2024-08-19 10:01:07 +05:00
public SetpointsRequestRepository(IAsbCloudDbContext dbContext, IMemoryCache memoryCache, IWellService wellService)
: base(dbContext, memoryCache, q => q.Include(s => s.Author)
.Include(s => s.Well))
{
this.wellService = wellService;
}
2024-08-19 10:01:07 +05:00
//TODO: заметка для рефакторинга. Использовать метод из базового репозитория
public virtual async Task<int> UpdateRangeAsync(IEnumerable<SetpointsRequestDto> dtos, CancellationToken token)
{
if (!dtos.Any())
return 0;
var ids = dtos
.Select(o => o.Id)
.Distinct()
.ToArray();
if (ids.Any(id => id == default))
throw new ArgumentInvalidException(nameof(dtos), "Все записи должны иметь Id");
if (ids.Length != dtos.Count())
throw new ArgumentInvalidException(nameof(dtos), "Все записи должны иметь уникальные Id");
var existingEntitiesCount = await dbContext.Set<SetpointsRequest>()
.Where(o => ids.Contains(o.Id))
.CountAsync(token);
if (ids.Length != existingEntitiesCount)
throw new ArgumentInvalidException(nameof(dtos), "Все записи должны существовать в БД");
2024-08-19 10:01:07 +05:00
var entities = dtos.Select(Convert);
var entries = entities.Select(entity => dbContext.Set<SetpointsRequest>().Update(entity)).ToList();
2024-08-19 10:01:07 +05:00
var affected = await dbContext.SaveChangesAsync(token);
entries.ForEach(entry => entry.State = EntityState.Detached);
2024-08-19 10:01:07 +05:00
if(affected > 0)
DropCache();
return affected;
}
2024-08-19 10:01:07 +05:00
protected override SetpointsRequestDto Convert(SetpointsRequest src)
{
var result = base.Convert(src);
var timezoneOffsetHours = wellService.GetTimezone(src.IdWell).Hours;
result.UploadDate = src.UploadDate.ToOffset(TimeSpan.FromHours(timezoneOffsetHours));
return result;
}
2024-08-19 10:01:07 +05:00
protected override SetpointsRequest Convert(SetpointsRequestDto src)
{
var result = base.Convert(src);
result.UploadDate = src.UploadDate.ToUniversalTime();
return result;
}
}