Fix Worker - Categorias
This commit is contained in:
@@ -174,16 +174,27 @@ public class Worker : BackgroundService
|
|||||||
var categoriasApi = await _apiService.GetCategoriasAsync(_authToken);
|
var categoriasApi = await _apiService.GetCategoriasAsync(_authToken);
|
||||||
if (categoriasApi is { Count: > 0 })
|
if (categoriasApi is { Count: > 0 })
|
||||||
{
|
{
|
||||||
|
// Primero, nos aseguramos de procesar solo IDs de categoría únicos desde la API
|
||||||
|
// para evitar conflictos de seguimiento en Entity Framework.
|
||||||
|
var distinctCategoriasApi = categoriasApi
|
||||||
|
.GroupBy(c => c.CategoriaId)
|
||||||
|
.Select(g => g.First()) // Tomamos la primera aparición de cada ID único
|
||||||
|
.ToList();
|
||||||
|
|
||||||
var categoriasEnDb = await dbContext.CategoriasElectorales.ToDictionaryAsync(c => c.Id, c => c, stoppingToken);
|
var categoriasEnDb = await dbContext.CategoriasElectorales.ToDictionaryAsync(c => c.Id, c => c, stoppingToken);
|
||||||
foreach (var categoriaDto in categoriasApi)
|
|
||||||
|
// Ahora iteramos sobre la lista depurada
|
||||||
|
foreach (var categoriaDto in distinctCategoriasApi)
|
||||||
{
|
{
|
||||||
if (categoriasEnDb.TryGetValue(categoriaDto.CategoriaId, out var categoriaExistente))
|
if (categoriasEnDb.TryGetValue(categoriaDto.CategoriaId, out var categoriaExistente))
|
||||||
{
|
{
|
||||||
|
// La categoría ya existe, actualizamos sus datos
|
||||||
categoriaExistente.Nombre = categoriaDto.Nombre;
|
categoriaExistente.Nombre = categoriaDto.Nombre;
|
||||||
categoriaExistente.Orden = categoriaDto.Orden;
|
categoriaExistente.Orden = categoriaDto.Orden;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
// La categoría es nueva, la añadimos
|
||||||
await dbContext.CategoriasElectorales.AddAsync(new CategoriaElectoral
|
await dbContext.CategoriasElectorales.AddAsync(new CategoriaElectoral
|
||||||
{
|
{
|
||||||
Id = categoriaDto.CategoriaId,
|
Id = categoriaDto.CategoriaId,
|
||||||
|
|||||||
Reference in New Issue
Block a user