diff --git a/AsbCloudInfrastructure/Repository/WitsRecordRepository.cs b/AsbCloudInfrastructure/Repository/WitsRecordRepository.cs index 1be9a7de..0c750c6b 100644 --- a/AsbCloudInfrastructure/Repository/WitsRecordRepository.cs +++ b/AsbCloudInfrastructure/Repository/WitsRecordRepository.cs @@ -66,17 +66,33 @@ namespace AsbCloudInfrastructure.Repository return new TDto[] { Convert(data, timezoneHours) }; } - public Task SaveDataAsync(int idTelemetry, IEnumerable dtos, CancellationToken token) + public async Task SaveDataAsync(int idTelemetry, IEnumerable dtos, CancellationToken token) { if (dtos?.Any() != true) - return Task.CompletedTask; + return; var timezoneHours = telemetryService.GetTimezone(idTelemetry).Hours; var entities = dtos .DistinctBy(d => d.DateTime) .Select(dto => Convert(dto, idTelemetry, timezoneHours)); - dbset.AddRange(entities); - return db.SaveChangesAsync(token); + + var dateMin = entities.Min(e => e.DateTime); + var dateMax = entities.Max(e => e.DateTime); + var existingEntities = await dbset + .Where(e => e.IdTelemetry == idTelemetry) + .Where(e => e.DateTime >= dateMin && e.DateTime <= dateMax) + .Select(e => new { e.DateTime, e.IdTelemetry}) + .ToArrayAsync(token); + + foreach (var entity in entities) + { + if (existingEntities.Any(e=>e.IdTelemetry == entity.IdTelemetry && e.DateTime == entity.DateTime)) + dbset.Update(entity); + else + dbset.Add(entity); + } + + await db.SaveChangesAsync(token); } private static TEntity Convert(TDto dto, int idTelemetry, double timezoneHours)