using Microsoft.EntityFrameworkCore; public class PatientPhiMigrationService : IHostedService { private const int BatchSize = 500; private readonly IServiceProvider _services; private readonly ILogger _logger; public PatientPhiMigrationService( IServiceProvider services, ILogger logger) { _services = services; _logger = logger; } public async Task StartAsync(CancellationToken ct) { using var scope = _services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var crypto = scope.ServiceProvider.GetRequiredService(); var totalMigrated = 0; Guid? afterId = null; while (!ct.IsCancellationRequested) { IQueryable query = db.Patients.OrderBy(p => p.Id); if (afterId is Guid cursor) query = query.Where(p => p.Id.CompareTo(cursor) > 0); var batch = await query.Take(BatchSize).ToListAsync(ct); if (batch.Count == 0) break; afterId = batch[^1].Id; var migrated = 0; foreach (var patient in batch) { if (patient.NameSearchToken is not null && crypto.IsEncrypted(patient.FirstName)) continue; patient.NameSearchToken = crypto.ComputeNameSearchToken( patient.FirstName, patient.LastName); migrated++; } if (migrated > 0) { await db.SaveChangesAsync(ct); totalMigrated += migrated; } db.ChangeTracker.Clear(); } if (totalMigrated > 0) { _logger.LogInformation( "PHI migration: updated {Count} patient search tokens", totalMigrated); } } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; }