v1.31.0
conocimientogenerador-crudtemplates/10.802 B

Configuration.cs.template

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

generador-crudskill
templatescarpeta
10.802 Btamaño
2026-10-03último cambio del pack
// ============================================================================
// TEMPLATE: Configuration.cs - Configuración EF Core (Fluent API)
// Skill: generador-crud
// ============================================================================
// USO: Reemplazar {{Entity}}, {{Entities}}, {{Namespace}}, {{Schema}}
// ============================================================================

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using {{Namespace}}.Domain.Entities;

namespace {{Namespace}}.Infrastructure.Persistence.Configurations;

/// <summary>
/// Configuración de EF Core para {{Entity}}
/// </summary>
public class {{Entity}}Configuration : IEntityTypeConfiguration<{{Entity}}>
{
    public void Configure(EntityTypeBuilder<{{Entity}}> builder)
    {
        // ═══════════════════════════════════════════════════════════════════
        // TABLA
        // ═══════════════════════════════════════════════════════════════════

        builder.ToTable("{{Entities}}", "{{Schema}}");

        // ═══════════════════════════════════════════════════════════════════
        // CLAVE PRIMARIA
        // ═══════════════════════════════════════════════════════════════════

        builder.HasKey(e => e.Id);

        builder.Property(e => e.Id)
            .ValueGeneratedOnAdd();

        // ═══════════════════════════════════════════════════════════════════
        // PROPIEDADES
        // ═══════════════════════════════════════════════════════════════════

        {{ConfiguracionPropiedades}}

        // ═══════════════════════════════════════════════════════════════════
        // PROPIEDADES DE AUDITORÍA
        // ═══════════════════════════════════════════════════════════════════

        builder.Property(e => e.CreatedAt)
            .IsRequired();

        builder.Property(e => e.CreatedBy)
            .HasMaxLength(256);

        builder.Property(e => e.ModifiedAt);

        builder.Property(e => e.ModifiedBy)
            .HasMaxLength(256);

        // ═══════════════════════════════════════════════════════════════════
        // SOFT DELETE
        // ═══════════════════════════════════════════════════════════════════

        builder.Property(e => e.IsDeleted)
            .HasDefaultValue(false);

        builder.Property(e => e.DeletedAt);

        builder.Property(e => e.DeletedBy)
            .HasMaxLength(256);

        // Query filter para soft delete
        builder.HasQueryFilter(e => !e.IsDeleted);

        // ═══════════════════════════════════════════════════════════════════
        // ÍNDICES
        // ═══════════════════════════════════════════════════════════════════

        {{ConfiguracionIndices}}

        // ═══════════════════════════════════════════════════════════════════
        // RELACIONES
        // ═══════════════════════════════════════════════════════════════════

        {{ConfiguracionRelaciones}}
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// PATRONES DE CONFIGURACIÓN COMUNES
// ═══════════════════════════════════════════════════════════════════════════

/*
// STRINGS
builder.Property(e => e.Name)
    .IsRequired()
    .HasMaxLength(200);

builder.Property(e => e.Description)
    .HasMaxLength(2000);

builder.Property(e => e.Code)
    .IsRequired()
    .HasMaxLength(20)
    .IsUnicode(false);  // VARCHAR en lugar de NVARCHAR

// DECIMALES
builder.Property(e => e.Amount)
    .HasPrecision(18, 2);  // DECIMAL(18,2)

builder.Property(e => e.Porcentaje)
    .HasPrecision(5, 2);   // DECIMAL(5,2)

// FECHAS
builder.Property(e => e.CreatedAt)
    .HasColumnType("datetime2(3)");  // Precisión de milisegundos

builder.Property(e => e.SoloFecha)
    .HasColumnType("date");

// ENUMS
builder.Property(e => e.Status)
    .HasConversion<string>()  // Guardar como string
    .HasMaxLength(50);

builder.Property(e => e.Tipo)
    .HasConversion<int>();    // Guardar como int (default)

// VALUE OBJECTS (Complex Types .NET 10)
builder.ComplexProperty(e => e.Period, p =>
{
    p.Property(x => x.StartDate).HasColumnName("StartDate");
    p.Property(x => x.EndDate).HasColumnName("EndDate");
});

// O como Owned Type (versiones anteriores)
builder.OwnsOne(e => e.Address, d =>
{
    d.Property(x => x.Calle).HasColumnName("Address_Calle").HasMaxLength(200);
    d.Property(x => x.City).HasColumnName("Address_City").HasMaxLength(100);
    d.Property(x => x.CodePostal).HasColumnName("Address_CP").HasMaxLength(10);
});

// ÍNDICES
builder.HasIndex(e => e.Code)
    .IsUnique()
    .HasDatabaseName("IX_{{Entities}}_Code");

builder.HasIndex(e => e.Status)
    .HasDatabaseName("IX_{{Entities}}_Estado");

builder.HasIndex(e => new { e.Status, e.CreatedAt })
    .HasDatabaseName("IX_{{Entities}}_Estado_Fecha");

// Índice filtrado (solo activos)
builder.HasIndex(e => e.Email)
    .IsUnique()
    .HasFilter("[IsDeleted] = 0")
    .HasDatabaseName("IX_{{Entities}}_Email");

// RELACIONES - Uno a Muchos
builder.HasMany(e => e.Applications)
    .WithOne(s => s.Scholarship)
    .HasForeignKey(s => s.ScholarshipId)
    .OnDelete(DeleteBehavior.Restrict);  // No cascade

// RELACIONES - Muchos a Uno
builder.HasOne(e => e.Category)
    .WithMany(c => c.{{Entities}})
    .HasForeignKey(e => e.CategoryId)
    .OnDelete(DeleteBehavior.Restrict);

// RELACIONES - Muchos a Muchos (EF Core 5+)
builder.HasMany(e => e.Tags)
    .WithMany(t => t.{{Entities}})
    .UsingEntity<Dictionary<string, object>>(
        "{{Entity}}Tag",
        j => j.HasOne<Tag>().WithMany().HasForeignKey("TagId"),
        j => j.HasOne<{{Entity}}>().WithMany().HasForeignKey("{{Entity}}Id"));

// CONVERSIONES PERSONALIZADAS
builder.Property(e => e.Metadata)
    .HasConversion(
        v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null!),
        v => JsonSerializer.Deserialize<Dictionary<string, string>>(v, (JsonSerializerOptions)null!)!
    );

// JSON COLUMN (.NET 10 / SQL Server 2022)
builder.OwnsOne(e => e.Configuracion, c =>
{
    c.ToJson();
});
*/

// ============================================================================
// EJEMPLO GENERADO - ScholarshipConfiguration
// ============================================================================
/*
public class ScholarshipConfiguration : IEntityTypeConfiguration<Scholarship>
{
    public void Configure(EntityTypeBuilder<Scholarship> builder)
    {
        builder.ToTable("Scholarships", "dbo");

        builder.HasKey(b => b.Id);

        builder.Property(b => b.Id)
            .ValueGeneratedOnAdd();

        // Propiedades
        builder.Property(b => b.Code)
            .IsRequired()
            .HasMaxLength(20)
            .IsUnicode(false);

        builder.Property(b => b.Name)
            .IsRequired()
            .HasMaxLength(200);

        builder.Property(b => b.Description)
            .HasMaxLength(2000);

        builder.Property(b => b.Amount)
            .HasPrecision(18, 2);

        builder.Property(b => b.Status)
            .HasConversion<string>()
            .HasMaxLength(20);

        builder.Property(b => b.StartDate)
            .HasColumnType("date");

        builder.Property(b => b.EndDate)
            .HasColumnType("date");

        // Auditoría
        builder.Property(b => b.CreatedAt).IsRequired();
        builder.Property(b => b.CreatedBy).HasMaxLength(256);
        builder.Property(b => b.ModifiedAt);
        builder.Property(b => b.ModifiedBy).HasMaxLength(256);

        // Soft delete
        builder.Property(b => b.IsDeleted).HasDefaultValue(false);
        builder.Property(b => b.DeletedAt);
        builder.Property(b => b.DeletedBy).HasMaxLength(256);
        builder.HasQueryFilter(b => !b.IsDeleted);

        // Índices
        builder.HasIndex(b => b.Code)
            .IsUnique()
            .HasDatabaseName("IX_Scholarships_Code");

        builder.HasIndex(b => b.Status)
            .HasDatabaseName("IX_Scholarships_Status");

        builder.HasIndex(b => new { b.Status, b.EndDate })
            .HasDatabaseName("IX_Scholarships_Status_EndDate");

        // Indice de la paginacion por keyset: MISMO orden que su ORDER BY (CreatedAt DESC, Id ASC).
        // Sin el, GetPageAsync ordena la tabla entera en cada pagina y keyset no aporta nada.
        builder.HasIndex(b => new { b.CreatedAt, b.Id })
            .HasDatabaseName("IX_Scholarships_CreatedAt_Id");

        // Relaciones
        builder.HasMany(b => b.Applications)
            .WithOne(s => s.Scholarship)
            .HasForeignKey(s => s.ScholarshipId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}
*/

← Volver a la ficha de generador-crud