v1.31.0
conocimientogenerador-crudtemplates/2892 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
2892 Btamaño
2026-10-03último cambio del pack
// ============================================================================
// TEMPLATE: Get{{Entity}}.cs - un caso de uso completo con procedimientos (por entidad)
// Skill: generador-crud, estilo vertical-slices con acceso por SP (ADR-054)
// ============================================================================
// USO: Reemplazar {{Entity}}, {{Entities}}, {{entities}}, {{Namespace}}, {{Schema}} 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.
//
// EN ESTE ESTILO EL FICHERO ENTERO SE DUPLICA POR MODO aunque solo cambie el handler, y es coherente
// con lo que el estilo promete: la unidad es la feature completa, no la capa. Es el precio de que
// cambiar una slice no arrastre a las demas, y aqui se paga con la tecnologia en vez de con la
// feature de al lado.
// ============================================================================

using System.Data;
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using {{Namespace}}.Common;

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

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

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

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

    public async Task<Result<Get{{Entity}}Response>> Handle(int id, CancellationToken ct = default)
    {
        // Dapper materializa la respuesta directamente: el procedimiento ya devuelve las columnas que
        // hacen falta, asi que no hay entidad por medio ni proyeccion que escribir.
        var fila = await _db.QuerySingleOrDefaultAsync<Get{{Entity}}Response>(new CommandDefinition(
            "{{Schema}}.Get{{Entity}}",
            new { Id = id },
            commandType: CommandType.StoredProcedure,
            cancellationToken: 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