SQLStoredProcedureCommandsFunctions 2.0.5
See the version list below for details.
dotnet add package SQLStoredProcedureCommandsFunctions --version 2.0.5
NuGet\Install-Package SQLStoredProcedureCommandsFunctions -Version 2.0.5
<PackageReference Include="SQLStoredProcedureCommandsFunctions" Version="2.0.5" />
<PackageVersion Include="SQLStoredProcedureCommandsFunctions" Version="2.0.5" />
<PackageReference Include="SQLStoredProcedureCommandsFunctions" />
paket add SQLStoredProcedureCommandsFunctions --version 2.0.5
#r "nuget: SQLStoredProcedureCommandsFunctions, 2.0.5"
#:package SQLStoredProcedureCommandsFunctions@2.0.5
#addin nuget:?package=SQLStoredProcedureCommandsFunctions&version=2.0.5
#tool nuget:?package=SQLStoredProcedureCommandsFunctions&version=2.0.5
SQLStoredProcedureCommandsFunctions 2.0.5
A lightweight, high-performance SQL Server data-access library for .NET 8, 9, and 10. Designed for enterprise applications and microservices that require clean, reusable database access with minimal boilerplate.
📦 Installation
Install from NuGet:
dotnet add package SQLStoredProcedureCommandsFunctions --version 2.0.5
Or via Package Manager:
Install-Package SQLStoredProcedureCommandsFunctions -Version 2.0.5
🚀 Key Features
- Automatic Resilient Retry Policy (
ISQLRetryPolicy,SQLRetryPolicy): Configurable retry handling for transient SQL Server and Azure SQL errors (deadlocks 1205, timeouts, throttling, network drops) with exponential backoff, jitter,CancellationTokensupport, and write-operation idempotency safety. - SQL Query Performance Monitoring (
ISQLPerformanceMonitor,SQLPerformanceMonitor): High-resolution monotonic execution timing, slow-query threshold alerts, timeout diagnostics, structured logging, distributed tracing (ActivitySource), and correlation tracking without leaking sensitive parameter values. - Advanced Multiple Result Set Mapping (
ExecuteMultipleAsync): Execute complex stored procedures returning multiple result sets and stream them directly into strongly-typed model collections (SQLMultipleResult<T1, T2, T3>) with tuple deconstruction(customers, orders, addresses). ZeroDataTableallocations, cached reflection, enum and Guid handling,[MapFrom]support, and clear missing result-set detection (SQLMissingResultSetException). - Dependency Injection Integration: Native
IServiceCollectionextension methods (AddSQLStoredProcedureFunctions) with options pattern (IOptions<SQLCommandsOptions>) andIConfigurationbinding. - Full Data Access Layer (
DataAccessLayer): Synchronous & asynchronous execution ofExecuteNonQuery,ExecuteScalar,ExecuteDataset,ExecuteReader, andExecuteXmlReader. Supports connection strings,SqlConnection, andSqlTransaction. - Strongly-Typed SP Mapper (
SQLSPResultMapper): Execute stored procedures once and map directly intoList<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 viaDeriveParameterswith thread-safe cloning. - SQL Parameter Utilities (
SQLParamHelper): Automatically generatesList<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.DataAccess |
DataAccessLayer, SQLHelperParameterCache |
SQLStoredProcedureCommandsFunctions.DataAccess.Mapping |
SQLMultipleResult, ISQLMultipleResultReader, SQLMultipleResultReader, SQLDataRecordMapper, SQLMissingResultSetException, SQLMappingException |
SQLStoredProcedureCommandsFunctions.DataAccess.Performance |
SQLPerformanceMonitor, SQLPerformanceOptions, SQLExecutionDiagnostics, ISQLPerformanceMonitor, SQLCorrelationContext |
SQLStoredProcedureCommandsFunctions.DataAccess.Resiliency |
SQLRetryPolicy, SQLRetryOptions, SQLTransientErrorDetector, ISQLRetryPolicy, SQLExecutionIntent |
SQLStoredProcedureCommandsFunctions.DataAccess.DependencyInjection |
ServiceCollectionExtensions, SQLCommandsOptions, ISQLStoredProcedureExecutor, SQLStoredProcedureExecutor, ISQLStoredProcedureExecutorFactory, SQLStoredProcedureExecutorFactory |
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. 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("@DepartmentId", 10)
);
// 2. Execute SP to a single record (Async)
UserDto? user = await SQLSPResultMapper.ExecuteSingleAsync<UserDto>(
connectionString,
CommandType.StoredProcedure,
"sp_GetUserById",
new("@UserId", 42)
);
// 3. Multi-table mapping: Multiple result sets to a tuple
(List<OrderDto> orders, List<OrderItemDto> items) = await SQLSPResultMapper.ExecuteMultiAsync<OrderDto, OrderItemDto>(
connectionString,
CommandType.StoredProcedure,
"sp_GetOrderWithItems",
new("@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
List<Dictionary<string, object>> 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"
);
2. 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 (Customer 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);
3. 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
SmartSQLBuilder 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 = SQLParamHelper.ToSqlParameters(result.Parameters);
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");
4. 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;
}
CreateUserCommand command = new()
{
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);
5. 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;
6. 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);
7. Core Data Access Layer (DataAccessLayer)
Low-level ADO.NET execution layer with overloads for connection strings, SqlConnection, and SqlTransaction.
using System.Data;
using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess;
// ExecuteNonQuery (Async)
int rowsAffected = await DataAccessLayer.ExecuteNonQueryAsync(
connectionString,
CommandType.StoredProcedure,
"sp_UpdateStatus",
new("@Id", 1),
new("@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"
);
8. Transaction Management (SQLHelper)
using SQLStoredProcedureCommandsFunctions.DataAccess.Utility;
SQLHelper.InitializeTransaction(connectionString);
try
{
// Execute multiple procedures using the active transaction...
SQLHelper.Commit();
}
catch
{
SQLHelper.RollBack();
throw;
}
9. Resilient Automatic Retry Policy & Dependency Injection
The package provides automated, configurable retry handling for transient SQL Server and Azure SQL failures (deadlocks, command execution timeouts, connection pooling drops, throttling).
ASP.NET Core / Microsoft.Extensions Dependency Injection
using Microsoft.Extensions.DependencyInjection;
using SQLStoredProcedureCommandsFunctions.DataAccess.DependencyInjection;
// In Program.cs:
builder.Services.AddSQLStoredProcedureFunctions(builder.Configuration, options =>
{
options.DefaultConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
options.DefaultCommandTimeoutSeconds = 30;
// Configure Retry Policy
options.Retry.Enabled = true;
options.Retry.MaxRetryAttempts = 3;
options.Retry.InitialDelay = TimeSpan.FromMilliseconds(500);
options.Retry.MaxDelay = TimeSpan.FromSeconds(10);
options.Retry.BackoffMultiplier = 2.0;
options.Retry.UseJitter = true;
options.Retry.RetryOnDeadlock = true; // Retries deadlock victim error (1205)
options.Retry.AllowWriteRetries = false; // Safety guard: prevents replaying non-idempotent writes
options.Retry.OnRetry = context =>
{
Console.WriteLine($"Retry {context.AttemptNumber}/{context.MaxRetryAttempts} " +
$"for {context.CommandText} after {context.Delay.TotalMilliseconds}ms delay. " +
$"Reason: {context.LastException.Message}");
};
});
Configuration via appsettings.json
{
"SqlCommands": {
"DefaultConnectionString": "Server=tcp:myserver.database.windows.net;Database=AppDb;...",
"DefaultCommandTimeoutSeconds": 30,
"Retry": {
"Enabled": true,
"MaxRetryAttempts": 3,
"InitialDelay": "00:00:00.500",
"MaxDelay": "00:00:10",
"BackoffMultiplier": 2.0,
"UseJitter": true,
"RetryOnDeadlock": true,
"AllowWriteRetries": false
}
}
}
Standalone & Static Usage (DataAccessLayer.RetryPolicy)
using SQLStoredProcedureCommandsFunctions.DataAccess;
using SQLStoredProcedureCommandsFunctions.DataAccess.Resiliency;
// Configure global retry policy on DataAccessLayer (if not using DI)
DataAccessLayer.RetryPolicy = new SQLRetryPolicy(new SQLRetryOptions
{
Enabled = true,
MaxRetryAttempts = 3,
InitialDelay = TimeSpan.FromMilliseconds(250),
MaxDelay = TimeSpan.FromSeconds(5)
});
// All DataAccessLayer and SQLSPResultMapper calls will automatically utilize the retry policy
DataTable dt = DataAccessLayer.ExecuteDataset(
commandText: "usp_GetCustomerData",
commandType: CommandType.StoredProcedure,
connectionString: connectionString,
parameters: [new("@CustomerId", 123)]
);
Transient Failure & Safety Behavior
- Recognized Transient Errors: Deadlock (
1205), command timeout (-2), Azure SQL throttling (40613,40197,40501,49918,49919,49920), resource limits (10928,10929), connection drops (10053,10054,10060,64,233,258), and network socket exceptions. - Strictly Excluded Errors: Syntax errors (
102,156), invalid column (207), missing object/table (208), missing stored procedure (2812), login/auth failures (18456), check constraints (547), duplicate key / unique constraint (2627,2601), and data truncation (8152). - Cancellation:
OperationCanceledExceptionand cancellation tokens immediately abort execution without retries. - Write Safety: Connection drops occurring before a command is sent are safe to retry. Mid-execution timeouts on write operations abort retries to prevent duplicate records unless explicitly permitted. Active transactions are not automatically retried.
10. SQL Query Performance Monitoring
The performance monitoring system captures monotonic query duration, slow-query warnings, failure/timeout tracking, and retry counts, while preventing sensitive parameter values from ever appearing in logs.
Configuration via Dependency Injection
services.AddSQLStoredProcedureFunctions(configuration, options =>
{
// Enable performance monitoring
options.Performance.EnableMonitoring = true;
options.Performance.SlowQueryThreshold = TimeSpan.FromSeconds(2);
options.Performance.LogAllCommands = true;
options.Performance.LogParameterNames = true; // Logs parameter names only; parameter values are NEVER logged
options.Performance.EnableActivitySource = true; // Built-in OpenTelemetry tracing
// Custom telemetry callback
options.Performance.OnExecutionCompleted = diagnostics =>
{
Console.WriteLine($"Command: {diagnostics.CommandText}, Duration: {diagnostics.DurationMs}ms, " +
$"Succeeded: {diagnostics.Succeeded}, IsSlow: {diagnostics.IsSlowQuery}, " +
$"Attempts: {diagnostics.AttemptCount}, CorrelationId: {diagnostics.CorrelationId}");
};
});
Ambient Correlation & Trace Context
using SQLStoredProcedureCommandsFunctions.DataAccess.Performance;
// Set ambient correlation identifier for downstream SQL executions
using (SQLCorrelationContext.SetCorrelationId("order-checkout-uuid-12345"))
{
// All DataAccessLayer or SQLSPResultMapper calls within this scope inherit the correlation ID
DataTable dt = DataAccessLayer.ExecuteDataset(connString, CommandType.StoredProcedure, "sp_ProcessOrder");
}
Structured Log Output Example
# Normal Completed Query (LogLevel.Information)
info: SQLStoredProcedureCommandsFunctions.DataAccess.Performance.SQLPerformanceMonitor[0]
SQL command completed. CommandName: dbo.GetCustomers, DurationMs: 34.2, Succeeded: true, IsSlowQuery: false, AttemptCount: 1, CorrelationId: 00-4bf92f3577b34da6a3ce929d0e0e4736-00bee804270cd40c-01
# Slow Query Warning (LogLevel.Warning)
warn: SQLStoredProcedureCommandsFunctions.DataAccess.Performance.SQLPerformanceMonitor[0]
SQL command completed (Slow Query). CommandName: dbo.GenerateAnnualReport, DurationMs: 2450.8, Succeeded: true, IsSlowQuery: true, AttemptCount: 1, CorrelationId: req-98765
# Failed / Timeout Query (LogLevel.Error)
fail: SQLStoredProcedureCommandsFunctions.DataAccess.Performance.SQLPerformanceMonitor[0]
SQL command failed. CommandName: dbo.ProcessBatch, DurationMs: 30005.1, Succeeded: false, AttemptCount: 3, CorrelationId: req-11223, IsTimeout: true, Error: Execution Timeout Expired.
11. Automatic Dependency Injection Support (AddSQLStoredProcedureFunctions)
Consumers can register, configure, and inject SQL execution components natively via IServiceCollection in ASP.NET Core, Worker Services, and Generic Host applications.
Service Registration (Program.cs)
using SQLStoredProcedureCommandsFunctions.DataAccess.DependencyInjection;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Register SQL Stored Procedure execution with connection string, retry, and monitoring
builder.Services.AddSQLStoredProcedureFunctions(
builder.Configuration,
options =>
{
options.ConnectionStringName = "DefaultConnection";
options.CommandTimeoutSeconds = 30;
options.Retry.Enabled = true;
options.Retry.MaxRetryAttempts = 3;
options.Performance.EnableMonitoring = true;
options.Performance.SlowQueryThreshold = TimeSpan.FromSeconds(2);
});
// Optional: Register a secondary/named database (e.g. for Reporting, Analytics, or Tenant-specific DBs)
builder.Services.AddSQLStoredProcedureFunctions(
"Reporting",
builder.Configuration,
options =>
{
options.ConnectionStringName = "ReportingConnection";
options.CommandTimeoutSeconds = 120;
});
// Register application repositories
builder.Services.AddScoped<ICustomerRepository, CustomerRepository>();
Sample Configuration (appsettings.json)
{
"ConnectionStrings": {
"DefaultConnection": "Server=tcp:sqlserver.database.windows.net;Database=CustomerDb;Authentication=Active Directory Default;TrustServerCertificate=True;",
"ReportingConnection": "Server=tcp:sqlserver.database.windows.net;Database=ReportingDb;Authentication=Active Directory Default;TrustServerCertificate=True;"
},
"SqlCommands": {
"DefaultCommandTimeoutSeconds": 30,
"Retry": {
"Enabled": true,
"MaxRetryAttempts": 3
},
"Performance": {
"EnableMonitoring": true,
"SlowQueryThreshold": "00:00:02"
}
}
}
Injecting ISQLStoredProcedureExecutor into Repositories
using System.Data;
using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess.DependencyInjection;
public class CustomerRepository(ISQLStoredProcedureExecutor sql, ILogger<CustomerRepository> logger) : ICustomerRepository
{
private readonly ISQLStoredProcedureExecutor _sql = sql ?? throw new ArgumentNullException(nameof(sql));
private readonly ILogger<CustomerRepository> _logger = logger ?? throw new ArgumentNullException(nameof(logger));
public async Task<List<Customer>> GetAllCustomersAsync(CancellationToken cancellationToken = default)
{
// Executes 'usp_GetAllCustomers' and maps result set to List<Customer>
return await _sql.ExecuteToListAsync<Customer>("usp_GetAllCustomers", cancellationToken);
}
public async Task<Customer?> GetCustomerByIdAsync(int id, CancellationToken cancellationToken = default)
{
// Executes SP with parameters and maps single record
return await _sql.ExecuteSingleAsync<Customer>(
"usp_GetCustomerById",
cancellationToken,
[new("@CustomerId", SqlDbType.Int) { Value = id }]);
}
public async Task<int> CreateCustomerAsync(Customer customer, CancellationToken cancellationToken = default)
{
SqlParameter[] parameters =
[
new("@Name", SqlDbType.NVarChar, 100) { Value = customer.Name },
new("@Email", SqlDbType.NVarChar, 255) { Value = customer.Email }
];
// Executes scalar returning new ID
object? result = await _sql.ExecuteScalarAsync("usp_CreateCustomer", cancellationToken, parameters);
return Convert.ToInt32(result);
}
}
Named Database Strategy (ISQLStoredProcedureExecutorFactory)
When working with multiple databases (e.g., Main database vs. Reporting or Audit database), resolve ISQLStoredProcedureExecutorFactory:
public class ReportingService(ISQLStoredProcedureExecutorFactory factory)
{
// Resolve executor for the named database configuration "Reporting"
private readonly ISQLStoredProcedureExecutor _reportingDb = factory.Create("Reporting");
public async Task<List<ReportSummary>> GetDailySummaryAsync(CancellationToken ct = default)
{
return await _reportingDb.ExecuteToListAsync<ReportSummary>("usp_GetDailySummary", ct);
}
}
Key Architecture & Lifetimes
- Scoped Lifetime for
ISQLStoredProcedureExecutor: Matches ASP.NET Core request scopes. - Connection Safety & Lifecycle:
ISQLStoredProcedureExecutordoes not keep open, long-livedSqlConnectioninstances. Each execution method internally instantiates a newusing SqlConnection conn = new(ConnectionString)block, opened asynchronously right before execution and disposed immediately upon return. - Full Async & CancellationToken Support: Every async method in
ISQLStoredProcedureExecutoraccepts an optionalCancellationTokenforwarded directly to ADO.NET and retry backoff delays. - Timeout & Connection Overrides: Consumers can derive ad-hoc scoped variants without mutating shared configurations using
executor.WithCommandTimeout(60)orexecutor.WithConnectionString(...). - Startup Validation:
SQLCommandsOptions.Validate()ensuresCommandTimeoutSeconds >= 0, valid retry parameters, and guarantees the target connection string exists at runtime. - Extensibility & Overrides: Consumers can register their own custom
ISQLRetryPolicy,ISQLPerformanceMonitor, or replaceISQLStoredProcedureExecutorvia DI container registration.
12. Advanced Stored Procedure Mapping for Multiple Result Sets (ExecuteMultipleAsync)
When a stored procedure returns multiple result sets, ExecuteMultipleAsync streams the results sequentially into strongly-typed model collections (IReadOnlyList<T>).
Key Capabilities
- Direct Data Streaming: Maps directly from
DbDataReader/SqlDataReaderwithout intermediateDataTableorDataSetmemory allocations. - Pre-Computed Ordinal Caching: Column-to-property ordinal lookup maps are computed once per result set, eliminating reflection on each row.
- Empty vs. Missing Result Sets: Accurately distinguishes between an empty result set (returns
[]) and a missing expected result set (throwsSQLMissingResultSetException). - Rich Type Coercions: Native support for enums (by name or integer value), Guids (from string, Guid, or byte[16]), nullable primitives,
DBNull,DateOnly,TimeOnly, and explicit column names via[MapFrom]. - Flexible Parameters: Pass parameters via anonymous objects (
new { CustomerId = 1 }), POCO models, dictionaries, orSqlParameter[]arrays. - Output Parameters & Transactions: Full support for
ParameterDirection.Outputand running inside ambient or explicitSqlTransactionboundaries.
Usage Example (CustomerRepository.cs via Dependency Injection)
using SQLStoredProcedureCommandsFunctions.DataAccess.DependencyInjection;
public class CustomerRepository(ISQLStoredProcedureExecutor sql)
{
private readonly ISQLStoredProcedureExecutor _sql = sql;
public async Task<CustomerDetailsDto?> GetCustomerDetailsAsync(int customerId, CancellationToken cancellationToken = default)
{
// Executes 'dbo.GetCustomerDetails' returning 3 result sets
SQLMultipleResult<CustomerDto, OrderDto, AddressDto> result = await _sql.ExecuteMultipleAsync<CustomerDto, OrderDto, AddressDto>(
"dbo.GetCustomerDetails",
new { CustomerId = customerId },
cancellationToken);
// Access via explicit order properties:
IReadOnlyList<CustomerDto> customers = result.First; // 1st Result Set
IReadOnlyList<OrderDto> orders = result.Second; // 2nd Result Set
IReadOnlyList<AddressDto> addresses = result.Third; // 3rd Result Set
// Or tuple deconstruction:
(IReadOnlyList<CustomerDto> cList, IReadOnlyList<OrderDto> oList, IReadOnlyList<AddressDto> aList) = result;
if (customers.Count == 0) return null;
return new CustomerDetailsDto
{
Customer = customers[0],
Orders = orders,
Addresses = addresses
};
}
}
Static & Standalone Usage (SQLSPResultMapper)
using SQLStoredProcedureCommandsFunctions.DataAccess.Utility;
// Static async call with anonymous parameter object
SQLMultipleResult<CustomerDto, OrderDto, AddressDto> result = await SQLSPResultMapper.ExecuteMultipleAsync<CustomerDto, OrderDto, AddressDto>(
connectionString,
"dbo.GetCustomerDetails",
new { CustomerId = 1 },
cancellationToken);
(IReadOnlyList<CustomerDto> customers, IReadOnlyList<OrderDto> orders, IReadOnlyList<AddressDto> addresses) = result;
Streaming Arbitrary Result Sets (ISQLMultipleResultReader)
When reading an arbitrary or dynamic number of result sets, use ExecuteMultipleReaderAsync:
await using SQLMultipleResultReader reader = await _sql.ExecuteMultipleReaderAsync(
"dbo.GetCustomerDetails",
new { CustomerId = 1 },
cancellationToken);
IReadOnlyList<CustomerDto> customers = await reader.ReadNextAsync<CustomerDto>(cancellationToken);
IReadOnlyList<OrderDto> orders = await reader.ReadNextAsync<OrderDto>(cancellationToken);
IReadOnlyList<AddressDto> addresses = await reader.ReadNextAsync<AddressDto>(cancellationToken);
Sample Stored Procedure (dbo.GetCustomerDetails)
CREATE OR ALTER PROCEDURE dbo.GetCustomerDetails
@CustomerId INT,
@TotalOrderCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
-- Result Set 1: Customer (CustomerDto)
SELECT CustomerId, Name, Email, CreditLimit, IsActive, CustomerGuid
FROM dbo.Customers
WHERE CustomerId = @CustomerId;
-- Result Set 2: Orders (OrderDto)
SELECT OrderId, CustomerId, TotalAmount, Status, OrderDate, ShippingNotes AS custom_notes_col
FROM dbo.Orders
WHERE CustomerId = @CustomerId
ORDER BY OrderDate DESC;
-- Result Set 3: Addresses (AddressDto)
SELECT AddressId, CustomerId, City, Country
FROM dbo.Addresses
WHERE CustomerId = @CustomerId;
-- Output Parameter
SELECT @TotalOrderCount = COUNT(1) FROM dbo.Orders WHERE CustomerId = @CustomerId;
END;
Handling Model Attributes ([MapFrom])
public class OrderDto
{
public int OrderId { get; set; }
public decimal TotalAmount { get; set; }
public OrderStatus Status { get; set; } // Enums mapped automatically
[MapFrom("custom_notes_col")] // Maps from database column 'custom_notes_col'
public string? Notes { get; set; }
}
🔄 End-to-End Data Flow
UI / API Filters
↓
SmartSQLBuilder (Fluent SQL + Parameters)
↓
DataAccessLayer / SQLSPResultMapper (Execution against SQL Server / Azure SQL)
↓
DataTable / SqlDataReader / DataSet
↓
DataTableMapper / DynamicAPIMapper (Attribute-based mapping)
↓
Strongly-Typed POCO Models (List<T>, Tuples, Dictionaries)
↓
JSON API Response / Business Layer
🛑 CancellationToken Support
All asynchronous operations across DataAccessLayer, ISQLStoredProcedureExecutor, SQLSPResultMapper, SQLHelper, SQLHelperParameterCache, SQLMultipleResultReader, SQLDataRecordMapper, ISQLRetryPolicy, and ISQLPerformanceMonitor support graceful cancellation via CancellationToken.
Passing a CancellationToken
using System.Data;
using Microsoft.Data.SqlClient;
using SQLStoredProcedureCommandsFunctions.DataAccess;
using SQLStoredProcedureCommandsFunctions.DataAccess.Utility;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// 1. DataAccessLayer (supports both positional and named cancellationToken)
int affected = await DataAccessLayer.ExecuteNonQueryAsync(
connectionString,
CommandType.StoredProcedure,
"dbo.UpdateInventory",
cancellationToken: cts.Token);
// 2. SQLSPResultMapper
List<UserDto> users = await SQLSPResultMapper.ExecuteToListAsync<UserDto>(
connectionString,
CommandType.StoredProcedure,
"dbo.GetUsers",
cts.Token,
new SqlParameter("@IsActive", true));
// 3. Bulk insert via SqlBulkCopy
await SQLSPResultMapper.ExecuteBulkInsertAsync<UserDto>(
connectionString,
usersTable,
"dbo.UsersStaging",
cts.Token);
// 4. Transactional async execution with automatic rollback on cancellation
await SQLHelper.ExecuteTransactionAsync(
connectionString,
async (conn, tran, ct) =>
{
await DataAccessLayer.ExecuteNonQueryAsync(
tran,
CommandType.StoredProcedure,
"dbo.DebitAccount",
ct,
new SqlParameter("@Amount", 100m));
},
cts.Token);
How Cancellation Works During SQL Execution
- Pre-execution check: Entry points validate
cancellationToken.ThrowIfCancellationRequested()before acquiring connections or starting retries. - Connection open & command execution: Tokens flow through
SqlConnection.OpenAsync(ct),SqlCommand.ExecuteNonQueryAsync(ct),SqlCommand.ExecuteScalarAsync(ct),SqlCommand.ExecuteReaderAsync(..., ct),SqlCommand.ExecuteXmlReaderAsync(ct),SqlDataReader.ReadAsync(ct),SqlDataReader.NextResultAsync(ct), andSqlBulkCopy.WriteToServerAsync(dt, ct). - Retry backoff:
SQLRetryPolicyaborts immediately on cancellation (OperationCanceledException) without retrying and forwards the token toISQLRetryDelayProvider.DelayAsync. - Resource cleanup: Connections, commands, readers, and transactions are disposed asynchronously (
await using/CloseAsync), and transactions are rolled back (RollbackAsync(CancellationToken.None)) when canceled mid-transaction.
ASP.NET Core Request Cancellation
Pass the controller or Minimal API CancellationToken (HttpContext.RequestAborted) directly into repositories and ISQLStoredProcedureExecutor:
[ApiController]
[Route("api/employees")]
public class EmployeesController(ISQLStoredProcedureExecutor sql) : ControllerBase
{
[HttpGet]
public async Task<IActionResult> GetEmployees(CancellationToken cancellationToken)
{
List<EmployeeDto> employees = await sql.ExecuteToListAsync<EmployeeDto>(
"dbo.GetEmployees",
cancellationToken);
return Ok(employees);
}
}
If the client disconnects or aborts the HTTP request, ASP.NET Core triggers cancellationToken, cancelling the active SQL query and releasing the pooled connection immediately.
Cancellation vs. Command Timeout
CommandTimeout(configured viaSQLCommandsOptions.CommandTimeoutSeconds,WithCommandTimeout(seconds), orSqlCommand.CommandTimeout) controls how long SQL Server is permitted to run a single command before ADO.NET throws a timeoutSqlException(Error-2).CancellationTokenreflects external or caller-driven cancellation (HTTP request aborted, host shutdown, user cancel) and raisesOperationCanceledException/TaskCanceledException.- Configuring or triggering a
CancellationTokennever overrides or resetsCommandTimeout. Timeouts (SqlExceptionError-2) remain eligible for transient retry policies, whereas cancellations (OperationCanceledException) abort immediately without retries.
Operations Without Native CancellationToken Support in ADO.NET / Microsoft.Data.SqlClient
Certain underlying ADO.NET APIs in Microsoft.Data.SqlClient / System.Data.Common do not expose native asynchronous CancellationToken execution:
SqlDataAdapter.Fill(DataSet)/SqlDataAdapter.Update(DataSet, string)(used byExecuteDatasetAsync,FillDataset,UpdateDataset, andSQLHelper.UpdateDS):SqlDataAdapterhas noFillAsyncorUpdateAsyncmethod. InExecuteDatasetAsync, connection opening usesOpenAsync(ct)natively, and an activeCancellationTokenRegistrationcallsSqlCommand.Cancel()duringFill(DataSet)so SQL Server cancels the active command and surfacesOperationCanceledException.DataTable.Load(IDataReader)(used bySQLSPResultMapper.ExecuteQueryAsync):OpenAsync(ct)andExecuteReaderAsync(ct)use native cancellation, and aCancellationTokenRegistrationcancels the underlyingSqlCommandif canceled while loading rows.SqlCommandBuilder.DeriveParameters(SqlCommand)(used on cache misses inSQLHelperParameterCache.GetSpParameterSetAsync):OpenAsync(ct)uses native cancellation andct.ThrowIfCancellationRequested()is checked before and after parameter derivation, thoughDeriveParametersitself is synchronous.SqlTransaction.CommitAsync(CancellationToken)/RollbackAsync(CancellationToken):SqlTransactioninheritsDbTransaction's baseCommitAsync/RollbackAsyncimplementations, which honor pre-cancelled tokens before delegating to synchronous TDS commit/rollback. Rollbacks insidecatchblocks invokeRollbackAsync(CancellationToken.None)so cancelled transactions still roll back cleanly.
🎯 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+),Microsoft.Extensions.Configuration(10.0.7+)
📄 License
This project is licensed under the MIT License.
| Product | Versions 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. |
-
net8.0
- Microsoft.Data.SqlClient (>= 7.0.1)
- Microsoft.Extensions.Configuration (>= 8.0.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Configuration.Binder (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.2)
- Microsoft.Extensions.Options (>= 8.0.2)
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.5 | 1,070 | 11/20/2025 |
Release Notes - v2.0.5 (2026-11-26)
✨ Major Features & Additions:
1. Automatic Resilient Retry Policy (ISQLRetryPolicy & SQLRetryPolicy)
- Configurable automatic retries for transient SQL Server and Azure SQL failures
(Deadlocks 1205, timeouts -2, throttling, network drops, Azure failover).
- Exponential backoff with customizable multiplier and randomized jitter (+/- 25%) to
prevent synchronized retry storms.
- Non-idempotent write safety guard: automatically aborts mid-execution write retries
unless explicitly enabled or verified as rolled-back deadlocks.
- Full CancellationToken propagation across database calls, bulk copy, transactions, readers, and retry backoff delays.
2. SQL Query Performance Monitoring & Diagnostics (ISQLPerformanceMonitor)
- Monotonic Stopwatch-based execution duration timing with zero allocation overhead.
- Slow-query detection and structured logging with configurable thresholds.
- Security-first parameter tracking: records parameter names while strictly excluding
sensitive parameter values.
- OpenTelemetry distributed tracing via ActivitySource
("SQLStoredProcedureCommandsFunctions").
- Ambient correlation tracking via SQLCorrelationContext (AsyncLocal<string?> and
Activity.Current fallback).
3. Automatic Dependency Injection (AddSQLStoredProcedureFunctions)
- Native IServiceCollection extension methods with options pattern
(IOptions<SQLCommandsOptions>).
- Scoped database executor (ISQLStoredProcedureExecutor) ensuring zero connection leaks
and pooled per-request lifecycles.
- Multi-database / named connection factory (ISQLStoredProcedureExecutorFactory).
4. Advanced Stored Procedure Multi-Result Mapping (ExecuteMultipleAsync)
- Direct streaming of complex multi-result stored procedures into strongly-typed POCO
collections (IReadOnlyList<T>) with zero DataTable allocations.
- Support for up to 5 generic result sets (SQLMultipleResult<T1, T2, ...>) with
direct tuple deconstruction:
(IReadOnlyList<CustomerDto> customers, IReadOnlyList<OrderDto> orders,
IReadOnlyList<AddressDto> addresses) = result;
- Pre-computed property reflection and column-ordinal caching per result set.
- Native support for Enums, Guids, Nullables, DateOnly, TimeOnly, and [MapFrom]
attribute mappings.
- Clear distinction between empty result sets and missing result sets
(SQLMissingResultSetException).
- Anonymous parameter object support: SQLParamHelper.ToSqlParameters(new { CustomerId =
1 }).
5. C# 12 & Modern Code Quality
- Modernized to C# 12 primary constructors across all classes and record structs.
- Clean, bracket-free single-line control flow syntax.
- Standardized all APIs to uppercase SQL naming convention.