v1.31.0
conocimientogenerador-crudtemplates/2317 B

LookupRepository.cs.template

Fichero que /hv:generador-crud usa o materializa en el proyecto. Se muestra tal cual está en el plugin.

generador-crudskill
templatescarpeta
2317 Btamaño
2026-10-03último cambio del pack
// ============================================================================
// TEMPLATE: LookupRepository.cs - Repositorio cacheado de catalogos (una vez por proyecto, opcional)
// Skill: generador-crud (ADR-031)
// ============================================================================
// USO: Reemplazar {{Namespace}}. Se genera si no existe; si ya existe no se toca.
// Destino: src/Infrastructure/Persistence/Repositories/CachedLookupQueries.cs
// Registro: services.AddMemoryCache(); services.AddScoped<ILookupQueries<ScholarshipType>, CachedLookupQueries<ScholarshipType>>();
// ============================================================================

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using {{Namespace}}.Application.Common.Interfaces;
using {{Namespace}}.Domain.Entities;

namespace {{Namespace}}.Infrastructure.Persistence.Queries;

public class CachedLookupQueries<T> : ILookupQueries<T> where T : LookupEntity
{
    private static readonly TimeSpan Ttl = TimeSpan.FromHours(1);
    private readonly ApplicationDbContext _context;
    private readonly IMemoryCache _cache;
    private readonly string _cacheKey = "Lookup_" + typeof(T).Name;

    public CachedLookupQueries(ApplicationDbContext context, IMemoryCache cache)
    {
        _context = context;
        _cache = cache;
    }

    public async Task<IReadOnlyList<T>> GetAllActiveAsync(CancellationToken ct = default)
    {
        var items = await _cache.GetOrCreateAsync(_cacheKey, async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = Ttl;
            return await _context.Set<T>()
                .AsNoTracking()
                .Where(e => e.IsActive)
                .OrderBy(e => e.SortOrder)
                .ThenBy(e => e.Name)
                .ToListAsync(ct);
        });
        return items ?? [];
    }

    public async Task<T?> GetByCodeAsync(string code, CancellationToken ct = default)
    {
        var items = await GetAllActiveAsync(ct);
        return items.FirstOrDefault(e => e.Code.Equals(code, StringComparison.OrdinalIgnoreCase));
    }

    public async Task<T?> GetByIdAsync(int id, CancellationToken ct = default)
    {
        var items = await GetAllActiveAsync(ct);
        return items.FirstOrDefault(e => e.Id == id);
    }
}

← Volver a la ficha de generador-crud