using Microsoft.EntityFrameworkCore;
namespace StellaOps.Provcache.Postgres;
public sealed partial class PostgresProvcacheRepository
{
///
public async Task UpsertAsync(ProvcacheEntry entry, CancellationToken cancellationToken = default)
{
var entity = MapToEntity(entry);
var existing = await _context.ProvcacheItems
.FirstOrDefaultAsync(e => e.VeriKey == entry.VeriKey, cancellationToken)
.ConfigureAwait(false);
if (existing is null)
{
_context.ProvcacheItems.Add(entity);
}
else
{
_context.Entry(existing).CurrentValues.SetValues(entity);
}
await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
///
public async Task UpsertManyAsync(IEnumerable entries, CancellationToken cancellationToken = default)
{
var entryList = entries.ToList();
if (entryList.Count == 0)
return;
var veriKeys = entryList.Select(e => e.VeriKey).ToList();
var existing = await _context.ProvcacheItems
.Where(e => veriKeys.Contains(e.VeriKey))
.ToDictionaryAsync(e => e.VeriKey, cancellationToken)
.ConfigureAwait(false);
foreach (var entry in entryList)
{
var entity = MapToEntity(entry);
if (existing.TryGetValue(entry.VeriKey, out var existingEntity))
{
_context.Entry(existingEntity).CurrentValues.SetValues(entity);
}
else
{
_context.ProvcacheItems.Add(entity);
}
}
await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
}