conocimientogenerador-crudtemplates/8007 B
Repository.cs.template
Fichero que /hv:generador-crud usa o materializa en el proyecto. Se muestra tal cual está en el plugin.
// ============================================================================
// TEMPLATE: {{Entity}}Repository.cs - capa de datos con Dapper y SQL propio (por entidad)
// Skill: generador-crud, estilo n capas con acceso por SQL (ADR-055)
// ============================================================================
// USO: Reemplazar {{Entity}}, {{Entities}}, {{Namespace}}, {{Schema}} y los fragmentos
// {{ColumnasSp}}, {{ValoresSpCrear}}, {{ParametrosSpCrear_Valores}}, {{AsignacionesSpActualizar}},
// {{ParametrosDapperCrear}}, {{ParametrosDapperActualizar}}
// Destino: src/Core/Data/{{Entity}}Repository.cs
//
// La interfaz es la MISMA que implementa el repositorio de EF Core y el de procedimientos: el
// servicio no cambia ni una linea al cambiar de modo, y eso es lo que la capa de datos existe para
// dar en este estilo.
//
// LA CONEXION NO SE ABRE AQUI: la da `IConnectionFactory`, que este modo REUTILIZA del modo
// `dapper-sp` sin copiarla (ver compartidas.json). Abrir una conexion no depende de donde viva el SQL.
//
// PARAMETRIZADO SIEMPRE: los valores viajan como parametros de Dapper (`@Name`), nunca interpolados
// en la cadena.
// ============================================================================
using Dapper;
using {{Namespace}}.Core.Entities;
namespace {{Namespace}}.Core.Data;
public interface I{{Entity}}Repository
{
Task<{{Entity}}?> GetByIdAsync(int id, CancellationToken ct = default);
Task<(IReadOnlyList<{{Entity}}> Items, int Total)> GetPageAsync(int page, int size, CancellationToken ct = default);
Task<{{Entity}}> AddAsync({{Entity}} entity, CancellationToken ct = default);
Task<bool> DeleteAsync(int id, CancellationToken ct = default);
Task<bool> ExistsNameAsync(string name, CancellationToken ct = default);
Task<bool> UpdateAsync(int id, {{Entity}} entity, CancellationToken ct = default);
}
public sealed class {{Entity}}Repository : I{{Entity}}Repository
{
/// <summary>Tope de pagina: sin el, un `size=100000` convierte el listado en un incidente.</summary>
private const int MaxPorPagina = 200;
// ─────────────────────────────────────────────────────────────────────── el SQL, en un solo sitio
private const string SqlGet = """
SELECT {{ColumnasSp}}
FROM {{Schema}}.{{Entities}}
WHERE Id = @Id;
""";
// El desempate por Id evita que una fila salte de pagina cuando dos comparten CreatedAt.
private const string SqlPagina = """
SELECT {{ColumnasSp}}
FROM {{Schema}}.{{Entities}}
ORDER BY CreatedAt DESC, Id ASC
OFFSET (@Page - 1) * @Size ROWS
FETCH NEXT @Size ROWS ONLY;
SELECT COUNT(*) FROM {{Schema}}.{{Entities}};
""";
private const string SqlCrear = """
INSERT INTO {{Schema}}.{{Entities}} ({{ValoresSpCrear}}, CreatedAt)
VALUES ({{ParametrosSpCrear_Valores}}, @CreatedAt);
SELECT CAST(SCOPE_IDENTITY() AS INT);
""";
private const string SqlActualizar = """
UPDATE {{Schema}}.{{Entities}}
SET {{AsignacionesSpActualizar}},
ModifiedAt = @ModifiedAt
WHERE Id = @Id;
SELECT @@ROWCOUNT;
""";
private const string SqlBorrar = """
DELETE FROM {{Schema}}.{{Entities}} WHERE Id = @Id;
SELECT @@ROWCOUNT;
""";
private const string SqlExisteNombre = """
SELECT CASE WHEN EXISTS (
SELECT 1 FROM {{Schema}}.{{Entities}} WHERE Name = @Name
) THEN 1 ELSE 0 END;
""";
// ───────────────────────────────────────────────────────────────────────
private readonly IConnectionFactory _conexiones;
public {{Entity}}Repository(IConnectionFactory conexiones) => _conexiones = conexiones;
public async Task<{{Entity}}?> GetByIdAsync(int id, CancellationToken ct = default)
{
using var cn = _conexiones.Crear();
return await cn.QuerySingleOrDefaultAsync<{{Entity}}>(
new CommandDefinition(SqlGet, new { Id = id }, cancellationToken: ct));
}
public async Task<(IReadOnlyList<{{Entity}}> Items, int Total)> GetPageAsync(
int page, int size, CancellationToken ct = default)
{
// page = 0 produciria un OFFSET negativo, que SQL Server rechaza.
page = Math.Max(1, page);
size = Math.Clamp(size, 1, MaxPorPagina);
using var cn = _conexiones.Crear();
// Los dos SELECT del mismo lote se leen en una sola ida a la base. Con dos llamadas separadas
// el total podria no corresponder a la pagina.
using var multi = await cn.QueryMultipleAsync(
new CommandDefinition(SqlPagina, new { Page = page, Size = size }, cancellationToken: ct));
var items = (await multi.ReadAsync<{{Entity}}>()).ToList();
var total = await multi.ReadSingleAsync<int>();
return (items, total);
}
public async Task<{{Entity}}> AddAsync({{Entity}} entity, CancellationToken ct = default)
{
// Las marcas de auditoria las ponia SaveChangesAsync del contexto. Sin ORM no hay quien las
// ponga, y las filas entrarian con la fecha por defecto -- que ademas empata en el ORDER BY
// del listado (ADR-053 D5). Aqui es donde vive esa responsabilidad en este modo.
entity.CreatedAt = DateTimeOffset.UtcNow;
using var cn = _conexiones.Crear();
entity.Id = await cn.ExecuteScalarAsync<int>(
new CommandDefinition(SqlCrear, {{ParametrosDapperCrear}}, cancellationToken: ct));
return entity;
}
public async Task<bool> DeleteAsync(int id, CancellationToken ct = default)
{
using var cn = _conexiones.Crear();
var filas = await cn.ExecuteScalarAsync<int>(
new CommandDefinition(SqlBorrar, new { Id = id }, cancellationToken: ct));
return filas > 0;
}
public async Task<bool> ExistsNameAsync(string name, CancellationToken ct = default)
{
using var cn = _conexiones.Crear();
return await cn.ExecuteScalarAsync<bool>(
new CommandDefinition(SqlExisteNombre, new { Name = name }, cancellationToken: ct));
}
public async Task<bool> UpdateAsync(int id, {{Entity}} entity, CancellationToken ct = default)
{
entity.ModifiedAt = DateTimeOffset.UtcNow;
using var cn = _conexiones.Crear();
var filas = await cn.ExecuteScalarAsync<int>(
new CommandDefinition(SqlActualizar, {{ParametrosDapperActualizar}}, cancellationToken: ct));
return filas > 0;
}
}
// ═══════════════════════════════════════════════════════════════════════════
// REGISTRO EN DI (en Program.cs)
// ═══════════════════════════════════════════════════════════════════════════
/*
builder.Services.AddScoped<I{{Entity}}Repository, {{Entity}}Repository>();
*/
// ═══════════════════════════════════════════════════════════════════════════
// INDICE QUE ESTE LISTADO NECESITA
// ═══════════════════════════════════════════════════════════════════════════
/*
CREATE INDEX IX_{{Entities}}_Orden ON {{Schema}}.{{Entities}} (CreatedAt DESC, Id ASC);
*/