JSolutionss.ORM.SqlServer 1.0.9

dotnet add package JSolutionss.ORM.SqlServer --version 1.0.9
                    
NuGet\Install-Package JSolutionss.ORM.SqlServer -Version 1.0.9
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="JSolutionss.ORM.SqlServer" Version="1.0.9" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="JSolutionss.ORM.SqlServer" Version="1.0.9" />
                    
Directory.Packages.props
<PackageReference Include="JSolutionss.ORM.SqlServer" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add JSolutionss.ORM.SqlServer --version 1.0.9
                    
#r "nuget: JSolutionss.ORM.SqlServer, 1.0.9"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package JSolutionss.ORM.SqlServer@1.0.9
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=JSolutionss.ORM.SqlServer&version=1.0.9
                    
Install as a Cake Addin
#tool nuget:?package=JSolutionss.ORM.SqlServer&version=1.0.9
                    
Install as a Cake Tool

JSolutionss.ORM.SqlServer

JSolutionss.ORM.SqlServer es un ORM de alto rendimiento para .NET 8 y SQL Server. Diseñado para arquitecturas empresariales, combina la velocidad de Dapper para mapeo de objetos y la eficiencia de SqlBulkCopy con streaming para operaciones masivas.

Implementa un patrón de segregación de responsabilidades basado en roles de base de datos (Query, Transaction, Log), optimizando el manejo de sockets y el pool de conexiones.

🚀 Características Principales

  • Alto Rendimiento: Mapeo rápido con Dapper y caché de consultas generadas.
  • Bulk Insert Streaming: Inserción masiva de IEnumerable<T> sin cargar DataTable en memoria.
  • Gestión Inteligente de Conexiones: Reuso eficiente del pool y control de sockets (await using).
  • Roles de Base de Datos: Soporte nativo para separar lecturas (Replica), escrituras (Master) y logs.
  • Logger con Failover: Guarda logs en BD (jss.AppLog) y hace fallback a archivo de texto automáticamente si la BD falla.
  • Configuración Aislada: Utiliza su propio archivo de configuración JSON para no contaminar el appsettings.json.

📦 Instalación

Instala el paquete desde tu feed NuGet:

dotnet add package JSolutionss.ORM.SqlServer

⚙️ Configuración

Registra el servicio en el contenedor de .NET. El método buscará automáticamente el archivo jsolutionss.ormsettings.json.

var builder = WebApplication.CreateBuilder(args);

// ... otros servicios ...

// Registra el ORM
builder.Services.AddJSolutionssORM();

// Opcional: Si deseas usar un nombre de archivo diferente (ej. por ambiente)
// builder.Services.AddJSolutionssORM("jsolutionss.production.json");

var app = builder.Build();

💻 Definición de Modelos

Utiliza los atributos incluidos en el namespace Mapping para vincular tus clases con las tablas SQL.

using JSolutionss.ORM.SqlServer.Mapping;

[Table("dbo.Productos")] // Nombre real de la tabla en SQL
public class Producto
{
    [Key] // Indica la Llave Primaria (Identity) para Updates automáticos
    public int IdProducto { get; set; }

    public string Nombre { get; set; }
    public string CodigoBarras { get; set; }
    public decimal Precio { get; set; }
    public bool Activo { get; set; }
}

Guía de Uso

El ORM expone la interfaz principal IServicioOperacionesDB, que agrupa las capacidades de lectura y escritura.

  1. Consultas (Query DB) Utiliza la conexión definida en stringConnectionQueryDB. Ideal para llenar Grids, Combos y Reportes.
public class ProductoService
{
    private readonly IServicioOperacionesDB _db;

    public ProductoService(IServicioOperacionesDB db)
    {
        _db = db;
    }

    public async Task<IEnumerable<Producto>> BuscarPorNombre(string nombre)
    {
        // Ejecuta Query directo o Stored Procedure.
        // Los parámetros anónimos se convierten automáticamente a @p_NombrePropiedad
        
        string sql = "SELECT * FROM dbo.Productos WHERE Nombre LIKE @p_Nombre AND Activo = 1";
        
        return await _db.ExecuteCollection<Producto>(
            spName: sql, 
            param: new { Nombre = $"%{nombre}%" }, 
            commandType: CommandType.Text
        );
    }
}
  1. Transacciones y CRUD (Transact DB)

Utiliza la conexión definida en stringConnectionTransactDB.

public async Task<int> InsertarProducto(Producto nuevoProducto)
{
    // Inserta el producto y retorna el Id generado
    return await _db.InsertAsync(nuevoProducto);
}
  1. Inserción Masiva (High Performance) Utiliza SqlBulkCopy con un IDataReader personalizado sobre tu lista, evitando cargar un DataTable en memoria.
public async Task ImportarExcel(List<Producto> listaMasiva)
{
    // Inserta miles de registros en segundos directamente a la tabla [Table]
    await _db.InsertListBulkCopy(listaMasiva);
}
  1. Logging y Auditoría
  • Inyecta ILogServiceDB para registrar eventos.
  • Automático: Si la tabla jss.AppLog no existe, el servicio la crea la primera vez.
  • Resiliente: Si la base de datos de logs cae, guarda el error en el archivo de texto configurado en jsolutionss.json.
public class LoggerService
{
    private readonly ILogServiceDB _logger;

    public LoggerService(ILogServiceDB logger)
    {
        _logger = logger;
    }

    public async Task RegistrarError(string mensaje, string stackTrace)
    {
        // Se requiere un modelo que coincida con la tabla de logs
        var log = new AppLogModel 
        { 
            Message = mensaje, 
            Level = "ERROR", 
            Exception = stackTrace,
            User = "System"
        };
        
        await _logger.Insert(log);
    }
}

📄 Convenciones Importantes

  • Parámetros SQL: El ORM antepone automáticamente el prefijo @p_ a los nombres de las propiedades de los objetos de parámetros. C#: new { IdEmpresa = 1 } SQL Esperado en SP o Query: @p_IdEmpresa
  • Mapeo: Es obligatorio usar el atributo [Table] en la clase.
  • Identidad: Es obligatorio usar el atributo [Key] en la propiedad de identidad para que los métodos Update y Insert funcionen correctamente.
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.9 131 4/7/2026
1.0.8 120 3/13/2026
1.0.7 125 1/2/2026
1.0.6 131 12/31/2025
1.0.5 128 12/31/2025
1.0.4 129 12/31/2025
1.0.3 124 12/31/2025
1.0.2 125 12/31/2025
1.0.1 161 12/26/2025
1.0.0 153 12/26/2025