conocimientogenerador-crudtemplates/5513 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 - acceso a datos por PROCEDIMIENTOS (por entidad)
// Skill: generador-crud, estilo n-layer, acceso dapper-sp (ADR-052)
// ============================================================================
// USO: Reemplazar {{Entity}}, {{Entities}}, {{Schema}}, {{Namespace}} y los fragmentos
// {{ParametrosDapperCrear}}, {{ParametrosDapperActualizar}}
// Destino: src/Core/Data/{{Entity}}Repository.cs
//
// EL CONTRATO ES EL MISMO que en el modo `efcore`: `I{{Entity}}Repository` no cambia ni una firma, y
// por eso `{{Entity}}Service` compila igual con los dos. Cambiar de modo de acceso a datos no toca la
// capa de negocio -- que es exactamente para lo que existe la interfaz.
//
// NI UNA SOLA CADENA SQL EN ESTE FICHERO. Solo nombres de procedimiento, y esos siguen la convencion
// `{schema}.{Accion}{Entidad}` que exige `sql-nomenclatura-guard`. Los procedimientos los genera la
// misma skill (plantilla sql/<motor>/Procedimientos.sql), asi que los nombres coinciden por
// construccion y no por acordarse.
//
// `CommandType.StoredProcedure` en TODAS las llamadas: sin el, Dapper manda el nombre como texto
// suelto y SQL Server lo interpreta como un lote, no como una invocacion.
// ============================================================================
using System.Data;
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 class {{Entity}}Repository : I{{Entity}}Repository
{
private const int MaxPorPagina = 200;
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("{{Schema}}.Get{{Entity}}", new { Id = id },
commandType: CommandType.StoredProcedure, cancellationToken: ct));
}
public async Task<(IReadOnlyList<{{Entity}}> Items, int Total)> GetPageAsync(
int page, int size, CancellationToken ct = default)
{
page = Math.Max(1, page);
size = Math.Clamp(size, 1, MaxPorPagina);
using var cn = _conexiones.Crear();
// El procedimiento devuelve DOS conjuntos -- la pagina y el total -- y 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("{{Schema}}.List{{Entities}}", new { Page = page, Size = size },
commandType: CommandType.StoredProcedure, 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). 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("{{Schema}}.Create{{Entity}}", {{ParametrosDapperCrear}},
commandType: CommandType.StoredProcedure, 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("{{Schema}}.Delete{{Entity}}", new { Id = id },
commandType: CommandType.StoredProcedure, 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("{{Schema}}.Exists{{Entity}}Name", new { Name = name },
commandType: CommandType.StoredProcedure, 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("{{Schema}}.Update{{Entity}}", {{ParametrosDapperActualizar}},
commandType: CommandType.StoredProcedure, cancellationToken: ct));
return filas > 0;
}
}