SQLStoredProcedureCommandsFunctions 2.0.4

There is a newer version of this package available.
See the version list below for details.
dotnet add package SQLStoredProcedureCommandsFunctions --version 2.0.4
                    
NuGet\Install-Package SQLStoredProcedureCommandsFunctions -Version 2.0.4
                    
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="SQLStoredProcedureCommandsFunctions" Version="2.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SQLStoredProcedureCommandsFunctions" Version="2.0.4" />
                    
Directory.Packages.props
<PackageReference Include="SQLStoredProcedureCommandsFunctions" />
                    
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 SQLStoredProcedureCommandsFunctions --version 2.0.4
                    
#r "nuget: SQLStoredProcedureCommandsFunctions, 2.0.4"
                    
#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 SQLStoredProcedureCommandsFunctions@2.0.4
                    
#: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=SQLStoredProcedureCommandsFunctions&version=2.0.4
                    
Install as a Cake Addin
#tool nuget:?package=SQLStoredProcedureCommandsFunctions&version=2.0.4
                    
Install as a Cake Tool

SQLStoredProcedureCommandsFunctions 2.0.4

NuGet Version Target Framework License: MIT

A lightweight, high-performance SQL Server and Azure SQL data-access library for .NET 8, 9, and 10. Designed for enterprise applications and microservices that require clean, reusable database access with minimal boilerplate, full Azure SQL Managed Identity support, and zero configuration for cloud deployments.


📦 Installation

Install from NuGet:

dotnet add package SQLStoredProcedureCommandsFunctions --version 2.0.4

Or via Package Manager:

Install-Package SQLStoredProcedureCommandsFunctions -Version 2.0.4

🚀 Key Features

  • Azure SQL Authentication (AzureCredential): Environment-aware token generation with automatic AccessToken injection into SqlConnection. Toggles seamlessly between local development (VisualStudioCredential) and cloud environments (DefaultAzureCredential / Managed Identity) with zero code changes.
  • Full Data Access Layer (DataAccessLayer): Synchronous & asynchronous execution of ExecuteNonQuery, ExecuteScalar, ExecuteDataset, ExecuteReader, and ExecuteXmlReader. Supports connection strings, SqlConnection, and SqlTransaction.
  • Strongly-Typed SP Mapper (SQLSPResultMapper): Execute stored procedures once and map directly into List<T>, IEnumerable<T>, multi-table collections, tuples, or dynamic dictionaries.
  • Dynamic Mapping Engine (DataTableMapper & DynamicAPIMapper): Attribute-based [MapFrom] column mapping, case-insensitive property matching, enum conversion, and nullable type support for both DataTables and JSON.
  • Fluent Query Builder (SmartSQLBuilder): Build SQL queries safely with parameterized filters (WhereIf, WhereIn, SearchLike), joins, grouping, sorting, pagination (OFFSET/FETCH), and static CRUD helpers (Insert, Update, Delete).
  • SP Parameter Caching (SQLHelperParameterCache): Automatically discovers and caches stored procedure parameters via DeriveParameters with thread-safe cloning.
  • SQL Parameter Utilities (SQLParamHelper): Automatically generates List<SqlParameter> from POCO models with CLR-to-SqlDbType inference and [IgnoreDbParameter] exclusion.
  • Conversion & TVP Utilities (DataAccessConverter & DataTableExtensions): Convert DataTables to/from strongly-typed collections, generate Table-Valued Parameters (TVP), convert DataSets to dictionaries, and reorder table columns.
  • Transaction Management (SQLHelper): Legacy-compatible transaction initialization, commit, and rollback utilities.

📂 Namespaces Overview

Namespace Primary Classes
SQLStoredProcedureCommandsFunctions.AzureHelper AzureCredential
SQLStoredProcedureCommandsFunctions.DataAccess DataAccessLayer, SQLHelperParameterCache
SQLStoredProcedureCommandsFunctions.DataAccess.Utility SQLSPResultMapper, SQLParamHelper, DataAccessConverter, DataTableExtensions, SQLHelper, IgnoreDbParameter
SQLStoredProcedureCommandsFunctions.DataAccess.SmartSQLBuilder SmartSQLBuilder, SmartSQLBuilderExtensions, SQLBuildResult
SQLStoredProcedureCommandsFunctions.DataAccess.DynamicAPIMapper DataTableMapper, DynamicAPIMapper, JSONHelper
SQLStoredProcedureCommandsFunctions.DataAccess.DynamicAPIMapper.Attributes MapFromAttribute

💡 Quick Examples & Usage Guide

1. Azure SQL Authentication & Managed Identity (AzureCredential)

AzureCredential enables passwordless authentication against Azure SQL Database and Azure SQL Managed Instance. It is environment-aware and injects access tokens directly into SqlConnection instances created by DataAccessLayer.

  • Local Development: Automatically utilizes VisualStudioCredential when running in Development with localhost.
  • Cloud Environments: Automatically uses DefaultAzureCredential (Managed Identity, Azure CLI, Service Principal) when deployed to Azure.
  • Zero Code Changes: No connection string passwords or credential switching needed between local and cloud environments.
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using SQLStoredProcedureCommandsFunctions.AzureHelper;
using SQLStoredProcedureCommandsFunctions.DataAccess;

// 1. Initialize once at startup (e.g., in Program.cs) with your IConfiguration
var azureCredential = new AzureCredential();
azureCredential.Initialize(builder.Configuration);

// 2. DataAccessLayer automatically acquires and assigns the Azure token to SqlConnection.AccessToken!
using SqlDataReader reader = await DataAccessLayer.ExecuteReaderAsync(
    azureSqlConnectionString,
    CommandType.StoredProcedure,
    "sp_GetUserData"
);

// 3. Or acquire the token manually if needed:
string accessToken = AzureCredential.GetToken();

2. Strongly-Typed Result Mapping (SQLSPResultMapper)

SQLSPResultMapper eliminates manual DataTable or SqlDataReader looping by automatically mapping stored procedure results to POCO models.

using System.Data;
using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess.Utility;

// 1. Execute SP to List<T> (Async)
List<UserDto> users = await SQLSPResultMapper.ExecuteToListAsync<UserDto>(
    connectionString,
    CommandType.StoredProcedure,
    "sp_GetUsers",
    new SqlParameter("@DepartmentId", 10)
);

// 2. Execute SP to a single record (Async)
UserDto? user = await SQLSPResultMapper.ExecuteSingleAsync<UserDto>(
    connectionString,
    CommandType.StoredProcedure,
    "sp_GetUserById",
    new SqlParameter("@UserId", 42)
);

// 3. Multi-table mapping: Multiple result sets to a tuple
var (orders, items) = await SQLSPResultMapper.ExecuteMultiAsync<OrderDto, OrderItemDto>(
    connectionString,
    CommandType.StoredProcedure,
    "sp_GetOrderWithItems",
    new SqlParameter("@OrderId", 1001)
);

// 4. Multi-table mapping: All tables to dictionary of lists
Dictionary<string, List<UserDto>> tables = await SQLSPResultMapper.ExecuteToMultiTableListAsync<UserDto>(
    connectionString,
    CommandType.StoredProcedure,
    "sp_GetMultiTableUsers"
);

// 5. Dynamic mapping to dictionaries
var dynamicData = await SQLSPResultMapper.ExecuteToDictionaryAsync(
    connectionString,
    CommandType.StoredProcedure,
    "sp_GetDynamicReport"
);
Output, InputOutput & ReturnValue Parameter Helpers
using System.Data;
using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess.Utility;

// Output parameter helper
SqlParameter outputParam = SQLSPResultMapper.Output("@TotalCount", SqlDbType.Int);

// InputOutput parameter helper
SqlParameter inputOutputParam = SQLSPResultMapper.InputOutput("@Counter", 5);

// Return value parameter helper
SqlParameter returnValueParam = SQLSPResultMapper.ReturnValue();

// Retrieve output values conveniently
int total = await SQLSPResultMapper.GetOutputAsync<int>(
    connectionString,
    CommandType.StoredProcedure,
    "sp_ProcessOrders",
    new[] { outputParam },
    "@TotalCount"
);

3. Dynamic Mapping Engine (DataTableMapper & DynamicAPIMapper)

Use the [MapFrom] attribute to map database column names (or JSON property keys) to custom C# property names. Mapping is case-insensitive and automatically converts DBNull, enums, and nullable types.

using System.Data;
using SQLStoredProcedureCommandsFunctions.DataAccess.DynamicAPIMapper;
using SQLStoredProcedureCommandsFunctions.DataAccess.DynamicAPIMapper.Attributes;

public class Customer
{
    public int Id { get; set; }

    [MapFrom("customer_full_name")] // Maps column "customer_full_name" to CustomerName
    public string CustomerName { get; set; } = string.Empty;

    public string? SalesOrg { get; set; }

    public CustomerStatus Status { get; set; }
}

public enum CustomerStatus
{
    Active = 1,
    Inactive = 2
}

// Map from DataTable to List<Customer>
DataTable dt = GetDataFromDatabase();
List<Customer> customers = DataTableMapper.MapToList<Customer>(dt);

foreach (var c in customers)
{
    Console.WriteLine($"{c.Id}: {c.CustomerName} ({c.Status})");
}

// Or map from JSON string using DynamicAPIMapper
string json = @"{ ""Id"": 10, ""customer_full_name"": ""Acme Corp"", ""SalesOrg"": ""US01"", ""Status"": ""Active"" }";
Customer customerFromJson = DynamicAPIMapper.Map<Customer>(json);

4. Smart SQL Query Builder (SmartSQLBuilder)

Fluent and SQL injection-safe query construction with support for conditional filters, parameterized WHERE IN and LIKE, sorting, pagination, and joins.

using System.Data;
using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess;
using SQLStoredProcedureCommandsFunctions.DataAccess.SmartSQLBuilder;

bool filterActiveOnly = true;

// 1. Build a parameterized SELECT query
var builder = new SmartSQLBuilder()
    .Select("Id", "Name", "SalesOrg")
    .From("Customers")
    .WhereIf(filterActiveOnly, "IsActive = 1")
    .SearchLike("Name", "Tech") // Parameterized LIKE: @Name_like = '%Tech%'
    .WhereIn("SalesOrg", new[] { "TW31", "TW32" }) // Parameterized IN: @SalesOrg_0, @SalesOrg_1
    .OrderBy("Id ASC")
    .Pagination(page: 1, pageSize: 10); // Generates: OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY

SQLBuildResult result = builder.Build();

Console.WriteLine("Generated SQL:");
Console.WriteLine(result.Query);

// 2. Execute query with DataAccessLayer using the generated parameters
SqlParameter[] sqlParams = result.Parameters
    .Select(p => new SqlParameter(p.Key, p.Value ?? DBNull.Value))
    .ToArray();

using SqlDataReader reader = await DataAccessLayer.ExecuteReaderAsync(
    connectionString,
    CommandType.Text,
    result.Query,
    sqlParams
);

while (await reader.ReadAsync())
{
    Console.WriteLine(reader["Name"]);
}
Static CRUD Helpers in SmartSQLBuilder
// INSERT statement and parameters
SQLBuildResult insert = SmartSQLBuilder.Insert("Customers", new { Name = "Contoso", SalesOrg = "US01" });

// UPDATE statement and parameters
SQLBuildResult update = SmartSQLBuilder.Update("Customers", new { Name = "Contoso Inc" }, "Id = @Id");

// DELETE statement
SQLBuildResult delete = SmartSQLBuilder.Delete("Customers", "Id = @Id");

5. Automatic SQL Parameter Generation (SQLParamHelper)

Generate List<SqlParameter> automatically from any C# POCO model. Skip unwanted properties using [IgnoreDbParameter].

using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess.Utility;

public class CreateUserCommand
{
    public string Username { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
    public int DepartmentId { get; set; }
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;

    [IgnoreDbParameter] // Will NOT be converted into a SqlParameter
    public string InternalToken { get; set; } = string.Empty;
}

var command = new CreateUserCommand
{
    Username = "tshah",
    Email = "tshah@example.com",
    DepartmentId = 1,
    InternalToken = "secret-token-123"
};

// Auto-converts to List<SqlParameter> with appropriate SqlDbType
List<SqlParameter> parameters = SQLParamHelper.GetSQLParameters(command);

// Create strongly typed single parameter
SqlParameter activeParam = SQLParamHelper.CreateSQLParameter("@IsActive", true);

6. Stored Procedure Parameter Caching (SQLHelperParameterCache)

Eliminates the performance overhead of repeated SqlCommandBuilder.DeriveParameters calls across application lifecycles.

using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess;

// Retrieves parameter set from cache or queries SQL Server once and caches it
SqlParameter[] parameters = SQLHelperParameterCache.GetSpParameterSet(connectionString, "sp_GetCustomerDetails");

// Assign parameter values and execute
parameters[0].Value = 101;

7. Data Conversion & TVP Utilities (DataAccessConverter & DataTableExtensions)

Convert between DataTables and generic collections or prepare Table-Valued Parameters (TVP) effortlessly.

using System.Data;
using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess.Utility;

List<Customer> customerList = GetCustomers();

// 1. Convert List<T> / IEnumerable<T> to DataTable
DataTable customerTable = DataAccessConverter.ConvertListToDataTable(customerList);

// 2. Create a Table-Valued Parameter (TVP) for stored procedures
SqlParameter tvpParam = DataAccessConverter.CreateTableTypeParameter(
    parameterName: "@CustomerTVP",
    data: customerList,
    typeName: "dbo.CustomerTableType"
);

// 3. Convert DataTable / DataSet to Dictionary collections
Dictionary<string, List<Dictionary<string, object>>> dsDict = 
    DataAccessConverter.ConvertDataSetToDictionary(myDataSet);

// 4. Extract distinct column values as a delimited string
string distinctSalesOrgs = DataAccessConverter.SelectDistinct(customerTable, "SalesOrg");

// 5. Column reordering via DataTableExtensions
customerTable.MoveColumnsToFront(targetIndex: 0, "Id", "CustomerName");
customerTable.MoveColumnsToIndex(new[] { "SalesOrg" }, targetIndex: 2);

8. Core Data Access Layer (DataAccessLayer)

Low-level ADO.NET execution layer with overloads for connection strings, SqlConnection, and SqlTransaction. Automatically attaches Azure tokens when connecting to Azure SQL.

using System.Data;
using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess;

// ExecuteNonQuery (Async)
int rowsAffected = await DataAccessLayer.ExecuteNonQueryAsync(
    connectionString,
    CommandType.StoredProcedure,
    "sp_UpdateStatus",
    new SqlParameter("@Id", 1),
    new SqlParameter("@Status", "Active")
);

// ExecuteScalar (Async)
object? scalarResult = await DataAccessLayer.ExecuteScalarAsync(
    connectionString,
    CommandType.Text,
    "SELECT COUNT(*) FROM Customers WHERE IsActive = 1"
);

// ExecuteDataset (Async)
DataSet dataSet = await DataAccessLayer.ExecuteDatasetAsync(
    connectionString,
    CommandType.StoredProcedure,
    "sp_GetAllCustomerData"
);

9. Transaction Management (SQLHelper)

using SQLStoredProcedureCommandsFunctions.DataAccess.Utility;

SQLHelper.InitializeTransaction(connectionString);
try
{
    // Execute multiple procedures using the active transaction...
    SQLHelper.Commit();
}
catch
{
    SQLHelper.RollBack();
    throw;
}

🔄 End-to-End Data Flow

  UI / API Filters
        ↓
  SmartSQLBuilder (Fluent SQL + Parameters)
        ↓
  DataAccessLayer / SQLSPResultMapper (Execution against SQL Server / Azure SQL via AzureCredential)
        ↓
  DataTable / SqlDataReader / DataSet
        ↓
  DataTableMapper / DynamicAPIMapper (Attribute-based mapping)
        ↓
  Strongly-Typed POCO Models (List<T>, Tuples, Dictionaries)
        ↓
  JSON API Response / Business Layer

🎯 Target Frameworks & Compatibility

  • Target Frameworks: .NET 8.0, .NET 9.0, .NET 10.0
  • Supported Databases: Microsoft SQL Server 2016+, Azure SQL Database, Azure SQL Managed Instance
  • Key Dependencies: Microsoft.Data.SqlClient (7.0.1+), Azure.Identity (1.21.0+), Microsoft.Extensions.Configuration (10.0.7+)

📄 License

This project is licensed under the MIT License.

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
2.0.6 62 11/26/2026
2.0.5 64 11/26/2026
2.0.4 149 10/14/2026
2.0.3 136 10/14/2026
2.0.2 115 10/10/2026
2.0.1 130 10/10/2026
1.0.9 244 4/28/2026
1.0.8 168 4/28/2026
1.0.7 181 3/23/2026
1.0.6 184 3/23/2026
1.0.5 185 2/23/2026
1.0.4 179 2/23/2026
1.0.1 395 12/16/2025
1.0.0.9 365 12/16/2025
1.0.0.8 782 12/3/2025
1.0.0.7 772 12/3/2025
1.0.0.6 2,136 11/20/2025 1.0.0.6 is deprecated because it is no longer maintained and has critical bugs.
1.0.0.5 1,070 11/20/2025 1.0.0.5 is deprecated because it is no longer maintained and has critical bugs.
Loading failed

Release Notes - v2.0.4

✨ Key Features

🔹 1. Azure SQL Authentication

Added AzureCredential helper with environment-aware token resolution.

Supports:
- Local development via VisualStudioCredential
- Cloud environments via DefaultAzureCredential
- Automatic access token generation for SQL connections.

(Files: AzureCredential.cs)


🔹 2. High-Performance Stored Procedure Execution

Execute NonQuery, Scalar, Reader, Dataset, XmlReader operations.

Full support for sync and async methods.

Overloads for:
- Raw SQL commands
- Stored procedure name
- Parameter arrays
- Strongly-typed object parameters


🔹 3. Built-In Transaction Support

Easy transaction lifecycle management:
- InitializeTransaction()
- Commit()
- Rollback()

Safe handling of shared connections.


🔹 4. Automatic SQL Parameter Discovery & Caching

SQLHelperParameterCache creates and caches stored procedure parameter sets.

- Avoids repeated trips to SQL Server using DeriveParameters.
- Provides deep clones to ensure thread-safety.
- Improves performance in high-load systems.


🔹 5. Object-to-SQL Parameter Mapping

SQLParamHelper allows:

- Auto-generation of SqlParameter list from an object.
- Support for numeric, string, GUID, datetime, boolean, and other primitives.
- Attribute [IgnoreDbParameter] to omit properties from mapping.
- Strongly typed parameter creation helpers.


🔹 6. SQLSPResultMapper – Strongly-Typed Result Mapping

Introduced SQLSPResultMapper to simplify stored procedure result handling.

Enables execution + automatic mapping into:

- List<T>
- IEnumerable<T>
- Dictionary<string, List<T>> (multi-table strong typing)
- Dictionary<string, List<Dictionary<string, object?>>> (dynamic mapping)
Supports:
- Sync & Async execution
- Case-insensitive column/property matching
- Nullable property handling
- DBNull → null conversion
- Multi-table stored procedures
- Clean integration with service-layer architecture

Eliminates repetitive DataTable-to-List conversion logic.

Designed for microservices and enterprise APIs.


🔹 7. DataSet & DataTable Conversion Utilities

Included in DataAccessConverter, offering:

Convert:
- DataTable → List<T>
- DataTable → IEnumerable<T>
- DataSet → Dictionary<string, List<object>>
- List<T> → DataTable
- Multiple lists → DataSet

Advanced helpers:
- Select distinct values
- Shift column ordering
- Move/rename table columns


🔹 8. Extension Methods for DataTable Manipulations

Included in DataTableExtensions:

- Move one or more columns to specific indices.
- Get column names by index.
- Reorder columns without breaking row data.


🔹 9. Streamlined Data Access Layer

The DataAccessLayer class provides a clean API for:

- Sync/async CRUD operations
- Command preparation
- Reader handling

Strong validation for:
- Connection state
- Null parameters
- Argument correctness

🔹 10. Dynamic Mapping Engine

Introduced [MapFrom] attribute for flexible column mapping

Supports DB column → custom property mapping

Case-insensitive mapping support

Handles nullable types and enums

🔹 11. Smart SQL Builder

Fluent SQL builder for SELECT, FROM, WHERE

Conditional filtering with WhereIf

IN / NOT IN support

LIKE / NOT LIKE helpers

Pagination support (OFFSET / FETCH)

Support for JOINs, GROUP BY, HAVING

Fully parameterized queries (SQL Injection safe)


🔧 Internal Enhancements

- Safe cloning of SQL parameters before execution.
- Consistent use of CommandTimeout for long-running procedures.
- Support for both internal and external connection ownership modes.
- Uses Microsoft.Data.SqlClient for modern SQL Server connectivity.
- Centralized execution pipeline reused by SQLSPResultMapper.


🐛 Known Limitations

- Does not support Dapper-style automatic mapping (future enhancement possible).
- SQL bulk copy not included in this version.
- Parameter type inference follows simplified rules and may need extension for complex types.
- Reflection-based mapping (expression-tree optimization planned for future release).


📦 Target Frameworks

-.NET 8, .NET 9, .NET 10


📘 Documentation

For full samples, including:
- CRUD examples
- Async patterns
- Stored procedure patterns
- Strongly-typed mapping examples
- Multi-table stored procedure handling