Modifica upsert dati

This commit is contained in:
Samuele E. Locatelli (W11-AI)
2026-04-07 18:46:28 +02:00
parent f86db5ff41
commit 6d575da0b7
3 changed files with 71 additions and 6 deletions
@@ -103,9 +103,42 @@ namespace MP.Data.Repository.Utils
}
// ora preparo inserimento massivo
await dbCtx
var existingRecords = await dbCtx
.DbSetStatsDet
.AddRangeAsync(listRecords);
.Where(x => listRecords.Select(r => new { r.Hour, r.Environment, r.Type }).Contains(new { Hour = x.Hour, Environment = x.Environment, Type = x.Type }))
.ToListAsync();
if (existingRecords.Count > 0)
{
var existingKeys = existingRecords.Select(r => new { r.Hour, r.Environment, r.Type }).ToHashSet();
var recordsToUpdate = listRecords.Where(r =>
existingKeys.Contains(new { Hour = r.Hour, Environment = r.Environment, Type = r.Type })).ToList();
var recordsToAdd = listRecords.Where(r =>
!existingKeys.Contains(new { Hour = r.Hour, Environment = r.Environment, Type = r.Type })).ToList();
foreach (var updateRec in recordsToUpdate)
{
var existing = existingRecords.First(x => x.Hour == updateRec.Hour && x.Environment == updateRec.Environment && x.Type == updateRec.Type);
existing.RequestCount = updateRec.RequestCount;
existing.AvgDuration = updateRec.AvgDuration;
existing.MaxDuration = updateRec.MaxDuration;
existing.MinDuration = updateRec.MinDuration;
existing.NoReply = updateRec.NoReply;
}
if (recordsToAdd.Count > 0)
{
await dbCtx.DbSetStatsDet.AddRangeAsync(recordsToAdd);
}
}
else
{
await dbCtx
.DbSetStatsDet
.AddRangeAsync(listRecords);
}
// salvo!
answ = await dbCtx.SaveChangesAsync();