SqlOptimizerHelper 1.0.0

dotnet add package SqlOptimizerHelper --version 1.0.0
                    
NuGet\Install-Package SqlOptimizerHelper -Version 1.0.0
                    
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="SqlOptimizerHelper" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SqlOptimizerHelper" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="SqlOptimizerHelper" />
                    
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 SqlOptimizerHelper --version 1.0.0
                    
#r "nuget: SqlOptimizerHelper, 1.0.0"
                    
#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 SqlOptimizerHelper@1.0.0
                    
#: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=SqlOptimizerHelper&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=SqlOptimizerHelper&version=1.0.0
                    
Install as a Cake Tool

SqlOptimizerHelper

NuGet Version License: MIT

SqlOptimizerHelper is a powerful Entity Framework Core extension that automatically detects and analyzes SQL performance issues in your applications. It provides real-time monitoring, detailed analysis, and actionable suggestions to optimize your database queries.

๐Ÿš€ Features

  • ๐Ÿ” Slow Query Detection - Automatically identifies queries exceeding performance thresholds
  • โš ๏ธ N+1 Query Detection - Detects and reports N+1 query problems with specific suggestions
  • ๐Ÿ“Š Missing Index Analysis - Analyzes WHERE clauses and suggests missing indexes
  • ๐Ÿ“ Real-time Console Logging - Immediate feedback with colored warnings and suggestions
  • ๐Ÿ“ˆ JSON Report Generation - Daily optimization reports with detailed statistics
  • โš™๏ธ Highly Configurable - Customizable thresholds, logging, and analysis settings
  • ๐Ÿ”ง Easy Integration - Simple one-line setup with your existing EF Core configuration

๐Ÿ“ฆ Installation

Install the package via NuGet Package Manager:

dotnet add package SqlOptimizerHelper

Or via Package Manager Console:

Install-Package SqlOptimizerHelper

๐ŸŽฏ Quick Start

Basic Usage

Add SqlOptimizerHelper to your EF Core configuration:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default"))
           .AddSqlOptimizer()); // ๐Ÿ‘ˆ Your optimization helper

Advanced Configuration

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default"))
           .AddSqlOptimizer(config =>
           {
               // Configure slow query threshold (default: 1000ms)
               config.SlowQueryThresholdMs = 500;
               
               // Enable/disable specific features
               config.EnableN1Detection = true;
               config.EnableIndexAnalysis = true;
               config.EnableSlowQueryDetection = true;
               
               // Configure logging
               config.EnableConsoleOutput = true;
               config.EnableJsonReports = true;
               config.LogPath = "./logs";
               
               // N+1 detection settings
               config.N1DetectionThreshold = 5; // Flag after 5 similar queries
               config.N1DetectionTimeWindowSeconds = 30; // Within 30 seconds
               
               // Application identification
               config.ApplicationName = "My E-Commerce App";
               config.Environment = "Production";
           }));

Configuration via appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=...;Database=MyDb;..."
  },
  "SqlOptimizer": {
    "SlowQueryThresholdMs": 1000,
    "EnableN1Detection": true,
    "EnableIndexAnalysis": true,
    "EnableSlowQueryDetection": true,
    "EnableConsoleOutput": true,
    "EnableJsonReports": true,
    "LogPath": "./logs",
    "N1DetectionThreshold": 5,
    "N1DetectionTimeWindowSeconds": 30,
    "ApplicationName": "My Application",
    "Environment": "Production"
  }
}

Then use it in your configuration:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default"))
           .AddSqlOptimizer(builder.Configuration));

๐Ÿ”Ž Detection Examples

Case 1: Slow Query Detection

Your Code:

var products = await _context.Products
    .Where(p => p.Name.Contains("phone"))
    .ToListAsync();

Generated SQL:

SELECT * FROM Products WHERE Name LIKE '%phone%'

SqlOptimizerHelper Output:

[SQL Optimizer] โš ๏ธ Slow query detected (3.4s)
    Warning: Slow query detected: 3400ms (threshold: 1000ms)
    Suggestion: Consider adding indexes on frequently queried columns; Review query execution plan for optimization opportunities

Case 2: N+1 Query Problem

Your Code:

var orders = await _context.Orders.ToListAsync();

foreach (var order in orders)
{
    var customer = await _context.Customers
        .FirstOrDefaultAsync(c => c.Id == order.CustomerId);
}

SqlOptimizerHelper Output:

[SQL Optimizer] โš ๏ธ N+1 Query Detected
    Warning: N+1 Query Detected: Customers queried 101 times in 30 seconds.
    Suggestion: Use 'Include()' to fetch related Customers data in one query. Example: context.Orders.Include(o => o.Customer).ToListAsync()

Case 3: Missing Index Detection

Your Code:

var products = await _context.Products
    .Where(p => p.Category == "Electronics")
    .ToListAsync();

SqlOptimizerHelper Output:

[SQL Optimizer] โšก MissingIndex detected
    Warning: No index on 'Products.Category'. Consider creating an index.
    Suggestion: CREATE INDEX IX_Products_Category ON Products(Category)

๐Ÿ“Š Report Generation

SqlOptimizerHelper automatically generates daily JSON reports in your specified log directory:

File: ./logs/sql-optimizer-report-2024-01-15.json

{
  "generatedAt": "2024-01-15T10:30:00Z",
  "applicationName": "My E-Commerce App",
  "environment": "Production",
  "analysisResults": [
    {
      "query": "SELECT * FROM Products WHERE Name LIKE '%phone%'",
      "executionTimeMs": 3400,
      "issueType": "SlowQuery",
      "severity": "High",
      "tableName": "Products",
      "columnName": "Name",
      "warning": "Slow query detected: 3400ms (threshold: 1000ms)",
      "suggestion": "Consider adding indexes on frequently queried columns",
      "timestamp": "2024-01-15T10:25:00Z"
    },
    {
      "issueType": "N+1",
      "severity": "High",
      "tableName": "Customers",
      "warning": "N+1 Query Detected: Customers queried 101 times in 30 seconds.",
      "suggestion": "Use 'Include()' to fetch related Customers data in one query"
    }
  ],
  "summary": {
    "totalQueries": 2,
    "slowQueries": 1,
    "n1Problems": 1,
    "missingIndexes": 0,
    "averageExecutionTimeMs": 1800,
    "slowestQueryMs": 3400,
    "totalExecutionTimeMs": 3600
  }
}

โš™๏ธ Configuration Options

Property Type Default Description
SlowQueryThresholdMs long 1000 Threshold in milliseconds for slow query detection
EnableN1Detection bool true Enable N+1 query problem detection
EnableIndexAnalysis bool true Enable missing index analysis
EnableSlowQueryDetection bool true Enable slow query detection
EnableConsoleOutput bool true Enable real-time console logging
EnableJsonReports bool true Enable JSON report generation
LogPath string "./logs" Directory for log files and reports
N1DetectionThreshold int 5 Minimum queries to trigger N+1 detection
N1DetectionTimeWindowSeconds int 30 Time window for N+1 detection
EnableDetailedSqlLogging bool false Log full SQL queries (security consideration)
MaxResultsInMemory int 1000 Maximum analysis results to keep in memory
ApplicationName string "Unknown" Application name for reports
Environment string "Development" Environment name for reports

๐Ÿ› ๏ธ Advanced Usage

Programmatic Access

// Get current analysis results
var results = SqlOptimizerService.GetAnalysisResults();

// Generate a report
var report = SqlOptimizerService.GenerateReport();

// Clear stored results
SqlOptimizerService.ClearResults();

// Check if service is registered
var isRegistered = SqlOptimizerService.IsRegistered();

Custom Analysis

// Access the interceptor directly
var interceptor = SqlOptimizerService.GetInterceptor();
if (interceptor != null)
{
    var results = interceptor.GetAnalysisResults();
    var report = interceptor.GenerateFinalReport();
}

๐Ÿงช Testing

The library includes comprehensive unit and integration tests. Run tests using:

dotnet test

๐Ÿ“ˆ Performance Impact

SqlOptimizerHelper is designed to have minimal performance impact:

  • Overhead: < 1ms per query in most cases
  • Memory Usage: Configurable limits prevent memory leaks
  • Async Operations: Logging and reporting are non-blocking
  • Production Ready: Safe to use in production environments

๐Ÿ”’ Security Considerations

  • SQL Logging: Disabled by default to prevent sensitive data exposure
  • Parameter Sanitization: Query parameters are sanitized in logs
  • File Permissions: Ensure proper permissions on log directories
  • Network Security: Reports are stored locally by default

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ†˜ Support

๐Ÿ™ Acknowledgments

  • Entity Framework Core team for the excellent interceptor infrastructure
  • .NET community for feedback and suggestions
  • Contributors and users who help improve this library

Made with โค๏ธ for the .NET community

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  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.0 190 10/16/2025

Initial release of SqlOptimizerHelper:
     - Slow query detection and analysis
     - N+1 query problem detection
     - Missing index suggestions
     - Real-time console logging
     - JSON report generation
     - Configurable thresholds and settings
     - Comprehensive EF Core integration