conocimientogenerador-crudtemplates/2699 B
Get.cs.template
Fichero que /hv:generador-crud usa o materializa en el proyecto. Se muestra tal cual está en el plugin.
// ============================================================================
// TEMPLATE: Get{{Entity}}.cs - un caso de uso completo con SQL propio (por entidad)
// Skill: generador-crud, estilo vertical-slices con acceso por SQL (ADR-055)
// ============================================================================
// USO: Reemplazar {{Entity}}, {{Entities}}, {{entities}}, {{Namespace}}, {{Schema}}, {{PropiedadesDto}}
// y {{ColumnasSp}}
// Destino: src/Features/{{Entities}}/Get{{Entity}}.cs
//
// LA SLICE TIENE SU CONSULTA, no solo su respuesta. Con EF Core cada slice escribia su proyeccion;
// aqui escribe su SELECT, que es la misma idea llevada un paso mas: si manana el detalle necesita una
// columna mas, se anade en este fichero y el listado no se entera.
// ============================================================================
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 const string Sql = """
SELECT {{ColumnasSp}}
FROM {{Schema}}.{{Entities}}
WHERE Id = @Id;
""";
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 SELECT ya trae 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(
Sql, new { Id = id }, 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;
}
}