Upsert con merge x dati aggregati (da provare)
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
using EgwCoreLib.Utils;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MP.Data.DbModels.Utils;
|
||||
using NLog;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -48,6 +49,85 @@ namespace MP.Data.Repository.Utils
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> UpsertManyAsync(List<StatsAggregatedModel> listRecords, bool removeOld)
|
||||
{
|
||||
if (listRecords == null || !listRecords.Any()) return 0;
|
||||
|
||||
int ans = 0;
|
||||
await using var dbCtx = await CreateContextAsync();
|
||||
await using var tx = await dbCtx.Database.BeginTransactionAsync();
|
||||
|
||||
try
|
||||
{
|
||||
// 1. Calcolo del range temporale della lista in arrivo per limitare la query di ricerca
|
||||
var minHour = listRecords.Min(x => x.Hour);
|
||||
var maxHour = listRecords.Max(x => x.Hour);
|
||||
|
||||
// 2. Se removeOld è true, manteniamo la logica originale (Eliminazione distruttiva)
|
||||
if (removeOld)
|
||||
{
|
||||
var itemsToRemove = await dbCtx.DbSetStatsAggr
|
||||
.Where(x => x.Hour >= minHour && x.Hour <= maxHour)
|
||||
.ToListAsync();
|
||||
if (itemsToRemove.Any())
|
||||
{
|
||||
dbCtx.DbSetStatsAggr.RemoveRange(itemsToRemove);
|
||||
await dbCtx.SaveChangesAsync(); // Commit parziale per la cancellazione
|
||||
}
|
||||
}
|
||||
|
||||
// 3. LOGICA DI UPSERT (Merge)
|
||||
// Recuperiamo tutti i record esistenti nel database che cadono nello stesso range temporale
|
||||
// Questo ci permette di confrontare ciò che arriva con ciò che è già presente.
|
||||
var existingRecords = await dbCtx.DbSetStatsAggr
|
||||
.Where(x => x.Hour >= minHour && x.Hour <= maxHour)
|
||||
.ToListAsync();
|
||||
|
||||
// Creiamo un dizionario per ricerca rapida O(1) basato sulla chiave univoca (Dest + Hour)
|
||||
// Usiamo una Tupla come chiave del dizionario
|
||||
var lookup = existingRecords.ToDictionary(
|
||||
x => (x.Destination, x.Hour),
|
||||
x => x
|
||||
);
|
||||
|
||||
foreach (var incoming in listRecords)
|
||||
{
|
||||
var key = (incoming.Destination, incoming.Hour);
|
||||
if (lookup.TryGetValue(key, out var existing))
|
||||
{
|
||||
// --- CASO: UPDATE ---
|
||||
existing.RequestCount = incoming.RequestCount;
|
||||
existing.AvgDuration = incoming.AvgDuration;
|
||||
existing.MinDuration = incoming.MinDuration;
|
||||
existing.MaxDuration = incoming.MaxDuration;
|
||||
// Aggiungi altri campi se presenti (es. NoReply, ecc.)
|
||||
}
|
||||
else
|
||||
{
|
||||
// --- CASO: INSERT ---
|
||||
await dbCtx.DbSetStatsAggr.AddAsync(incoming);
|
||||
}
|
||||
}
|
||||
// 4. Salvataggio finale
|
||||
ans = await dbCtx.SaveChangesAsync();
|
||||
|
||||
// Commit della transazione
|
||||
await tx.CommitAsync();
|
||||
|
||||
// Pulizia memoria per evitare che il ChangeTracker diventi troppo pesante nei loop lunghi
|
||||
dbCtx.ChangeTracker.Clear();
|
||||
|
||||
return ans;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await tx.RollbackAsync();
|
||||
Log.Error(ex, "Error during UpsertManyAsync");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> UpsertManyAsyncOrig(List<StatsAggregatedModel> listRecords, bool removeOld)
|
||||
{
|
||||
int answ = 0;
|
||||
await using var dbCtx = await CreateContextAsync();
|
||||
@@ -103,5 +183,11 @@ namespace MP.Data.Repository.Utils
|
||||
}
|
||||
|
||||
#endregion Public Methods
|
||||
|
||||
#region Protected Fields
|
||||
|
||||
protected static NLog.Logger Log = LogManager.GetCurrentClassLogger();
|
||||
|
||||
#endregion Protected Fields
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user