v1.31.0
conocimientogenerador-crudtemplates/2534 B

Get.cs.template

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

generador-crudskill
templatescarpeta
2534 Btamaño
2026-10-03último cambio del pack
// ============================================================================
// TEMPLATE: Get{{Entity}}.cs - un caso de uso completo (por entidad)
// Skill: generador-crud, estilo vertical-slices (ADR-049)
// ============================================================================
// USO: Reemplazar {{Entity}}, {{Entities}}, {{entities}}, {{Namespace}} y {{PropiedadesDto}}
// Destino: src/Features/{{Entities}}/Get{{Entity}}.cs
//
// La lectura por id trae su PROPIA respuesta. No hay un {{Entity}}Dto compartido por todas las
// slices: si manana el detalle necesita un campo mas, se anade aqui y no se toca el listado. Ese es
// el intercambio del estilo -- algo de repeticion entre slices a cambio de que cambiar una no
// arrastre a las demas.
// ============================================================================

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using {{Namespace}}.Common;
using {{Namespace}}.Persistence;

namespace {{Namespace}}.Features.{{Entities}};

public sealed record Get{{Entity}}Response
{
    public int Id { get; init; }
    {{PropiedadesDto}}
}

public sealed class Get{{Entity}}Handler
{
    private readonly AppDbContext _db;

    public Get{{Entity}}Handler(AppDbContext db) => _db = db;

    public async Task<Result<Get{{Entity}}Response>> Handle(int id, CancellationToken ct = default)
    {
        // Se proyecta en la consulta: solo viajan las columnas que la respuesta necesita.
        var fila = await _db.{{Entities}}
            .AsNoTracking()
            .Where(e => e.Id == id)
            .Select(e => new Get{{Entity}}Response { Id = e.Id })
            .FirstOrDefaultAsync(ct);

        return fila is null
            ? Result<Get{{Entity}}Response>.NotFound($"{{Entity}} {id} does not exist.")
            : Result<Get{{Entity}}Response>.Ok(fila);
    }
}

public static class Get{{Entity}}Endpoint
{
    public static IEndpointRouteBuilder MapGet{{Entity}}(this IEndpointRouteBuilder rutas)
    {
        rutas.MapGet("/api/v1/{{entities}}/{id:int}", async (
            int id,
            Get{{Entity}}Handler handler,
            CancellationToken ct) =>
        {
            var resultado = await handler.Handle(id, ct);
            return resultado.Succeeded ? Results.Ok(resultado.Value) : resultado.ToProblem();
        })
        .WithName("Get{{Entity}}")
        .Produces<Get{{Entity}}Response>()
        .ProducesProblem(StatusCodes.Status404NotFound);

        return rutas;
    }
}

← Volver a la ficha de generador-crud