From 76b1cc2f1f2e9b1f742dcc4606352d42e9131750 Mon Sep 17 00:00:00 2001 From: ngfrolov Date: Wed, 20 Sep 2023 17:50:44 +0500 Subject: [PATCH] Fix GtrWitsRepository.SaveDataAsync() ignoring duplicates and other exception --- .../Repository/GtrWitsRepository.cs | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/AsbCloudInfrastructure/Repository/GtrWitsRepository.cs b/AsbCloudInfrastructure/Repository/GtrWitsRepository.cs index 12b97ea7..2a871553 100644 --- a/AsbCloudInfrastructure/Repository/GtrWitsRepository.cs +++ b/AsbCloudInfrastructure/Repository/GtrWitsRepository.cs @@ -1,12 +1,14 @@ using AsbCloudApp.Data.GTR; using AsbCloudApp.Repositories; using AsbCloudApp.Services; +using AsbCloudDb; using AsbCloudDb.Model; using AsbCloudDb.Model.GTR; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -149,6 +151,10 @@ namespace AsbCloudInfrastructure.Repository var cacheTelemetryItems = cache.GetValueOrDefault(idTelemetry); + var strings = new List(4); + var floats = new List(4); + var ints = new List(4); + foreach (var record in dtos) { var dateTime = record.Date.ToUtcDateTimeOffset(timezoneHours); @@ -161,30 +167,35 @@ namespace AsbCloudInfrastructure.Repository if (item.Value.Value is string valueString) { var entity = MakeEntity(record.Id, item.Key, idTelemetry, dateTime, valueString); - db.WitsItemString.Add(entity); + strings.Add(entity); } if (item.Value.Value is float valueFloat) { var entity = MakeEntity(record.Id, item.Key, idTelemetry, dateTime, valueFloat); - db.WitsItemFloat.Add(entity); + floats.Add(entity); } if (item.Value.Value is int valueInt) { var entity = MakeEntity(record.Id, item.Key, idTelemetry, dateTime, valueInt); - db.WitsItemInt.Add(entity); + ints.Add(entity); } } } try { - await db.SaveChangesAsync(token); + if (strings.Any()) + await db.Database.ExecInsertOrIgnoreAsync(db.Set(), strings, token); + + if (floats.Any()) + await db.Database.ExecInsertOrIgnoreAsync(db.Set(), floats, token); + + if (ints.Any()) + await db.Database.ExecInsertOrIgnoreAsync(db.Set(), ints, token); } - catch(DbUpdateException ex) + catch(Exception ex) { - var isRelational = ex.Source == "Microsoft.EntityFrameworkCore.Relational" && ex.Entries.Any(); - if (!isRelational) - throw; + Trace.TraceError("Exception while saving GTR Wits data", ex); } cache.AddOrUpdate(idTelemetry,